树莓派 python 百度语音控制 gpio 控制开关灯

  • 2019 年 11 月 28 日
  • 筆記

最初拿到树莓派的时候测试过,没成功,后来发现一张华丽丽的说明图,顿时醒悟了..记录下来,

主要学习自  : http://blog.csdn.net/xdw1985829/article/details/39580401/

一定要看这个图,不然找不到io口的位置和编号

1、安装

Python2安装GPIO库需要输入命令:

sudo apt-get install python-dev  sudo apt-get install python-rpi.gpio

Python3安装GPIO库需要输入命令

sudo apt-get install python-dev  sudo apt-get install python3-rpi.gpio

2 测试gpio

建立一个测试文件,test.py

然后运行之:  sudo python test.py

注意:首先要sudo 要有管理员权限才能控制io口.其次你的连线得注意一下,下面gpio.high是代表11口输出高电平,大概不到3.3的电压,而且电流也比较小,一般而言是用作继电器或者放大电路中的信号元.

# -*- coding: utf-8 -*-  import RPi.GPIO as GPIO  import time  # BOARD编号方式,基于插座引脚编号  GPIO.setmode(GPIO.BOARD)  # 输出模式  GPIO.setup(11, GPIO.OUT)    while True:      GPIO.output(11, GPIO.HIGH)      time.sleep(1)      GPIO.output(11, GPIO.LOW)      time.sleep(1)

如果你能出现灯光闪烁,那么就算是成功拉,

3.语音部分

主要部分请参照这文章,还有之前有很多可以

python语音智能对话聊天机器人,linux&&树莓派双平台兼容

然后在其中加入判断就可以了

注意”开门后面的逗号要中文编码下的逗号”

if(cmp(duihua,'开门,')==0):      print "识别开门"      GPIO.output(11, GPIO.LOW)
if(cmp(duihua,'关门,')==0):      print "识别关门"      GPIO.output(11, GPIO.HIGH)

注意在开头要加上下面的申明.

# -*- coding: utf-8 -*-  import RPi.GPIO as GPIO  import time  # BOARD编号方式,基于插座引脚编号  GPIO.setmode(GPIO.BOARD)  # 输出模式  GPIO.setup(11, GPIO.OUT)

4.树莓派下源代码

说明:环境挺麻烦,请看前面给出的链接,然后需要将建立文件夹:yuyinduihua 放在/home/pi 下,因为下面有使用绝对路径的地方,.需要调整.

有可能出错的地方是百度语音的token需要自己粘帖上去..这个有点懒的改了.

.就是在这里后面tok的一串数字是他的识别码,过一段时间就会更换,失效,所以需要自己输出token函数的内容,然后再粘帖过去,,希望还是需要多学习一下之前几篇关于百度语音的才能控制自如.

url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=1&spd=7&cuid=7519663&ctp=1&tok=24.ece6cfa6b5821f481deceef114da892e.2592000.1467287744.282335-7519663"
# -*- coding: utf-8 -*-  #from pyaudio import PyAudio, paInt16  import numpy as np  from datetime import datetime  import wave  import time  import urllib, urllib2, pycurl  import base64  import json  import os  import sys  import RPi.GPIO as GPIO  import time  # BOARD编号方式,基于插座引脚编号  GPIO.setmode(GPIO.BOARD)  # 输出模式  GPIO.setup(11, GPIO.OUT)    reload(sys)  sys.setdefaultencoding( "utf-8" )    save_count = 0  save_buffer = []  t = 0  sum = 0  time_flag = 0  flag_num = 0  filename = '2.wav'  duihua = '1'  def getHtml(url):      page = urllib.urlopen(url)      html = page.read()      return html    def get_token():      apiKey = "Ll0c53MSac6GBOtpg22ZSGAU"      secretKey = "44c8af396038a24e34936227d4a19dc2"      auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;      res = urllib2.urlopen(auth_url)      json_data = res.read()      return json.loads(json_data)['access_token']    def dump_res(buf):      global duihua      print "字符串类型"      print (buf)      a = eval(buf)      print type(a)      if a['err_msg']=='success.':          #print a['result'][0]#终于搞定了,在这里可以输出,返回的语句          duihua = a['result'][0]          print duihua    def use_cloud(token):      fp = wave.open(filename, 'rb')      nf = fp.getnframes()      f_len = nf * 2      audio_data = fp.readframes(nf)      cuid = "7519663" #产品id      srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token      http_header = [          'Content-Type: audio/pcm; rate=8000',          'Content-Length: %d' % f_len      ]        c = pycurl.Curl()      c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode      #c.setopt(c.RETURNTRANSFER, 1)      c.setopt(c.HTTPHEADER, http_header)   #must be list, not dict      c.setopt(c.POST, 1)      c.setopt(c.CONNECTTIMEOUT, 30)      c.setopt(c.TIMEOUT, 30)      c.setopt(c.WRITEFUNCTION, dump_res)      c.setopt(c.POSTFIELDS, audio_data)      c.setopt(c.POSTFIELDSIZE, f_len)      c.perform() #pycurl.perform() has no return val    # 将data中的数据保存到名为filename的WAV文件中  def save_wave_file(filename, data):      wf = wave.open(filename, 'wb')      wf.setnchannels(1)      wf.setsampwidth(2)      wf.setframerate(SAMPLING_RATE)      wf.writeframes("".join(data))      wf.close()      NUM_SAMPLES = 2000      # pyAudio内部缓存的块的大小  SAMPLING_RATE = 8000    # 取样频率  LEVEL = 1500            # 声音保存的阈值  COUNT_NUM = 20          # NUM_SAMPLES个取样之内出现COUNT_NUM个大于LEVEL的取样则记录声音  SAVE_LENGTH = 8         # 声音记录的最小长度:SAVE_LENGTH * NUM_SAMPLES 个取样      token = get_token()  key = '05ba411481c8cfa61b91124ef7389767'  api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='      while(True):      print "kaishi"      os.system('arecord -D "plughw:1,0" -f S16_LE -d 3 -r 8000 /home/pi/yuyinduihua/2.wav')      use_cloud(token)      print "输入内容"      print duihua      ############      #语音识别进行开门的设置#      ############      if(cmp(duihua,'开门,')==0):           print "识别开门"           GPIO.output(11, GPIO.LOW)        info = duihua      duihua = ""      request = api + info      response = getHtml(request)      dic_json = json.loads(response)        #print '机器人: '.decode('utf-8') + dic_json['text']      #huida = ' '.decode('utf-8') + dic_json['text']      a = dic_json['text']      print type(a)      unicodestring = a        # 将Unicode转化为普通Python字符串:"encode"      utf8string = unicodestring.encode("utf-8")        print type(utf8string)      print str(a)      url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=1&spd=7&cuid=7519663&ctp=1&tok=24.ece6cfa6b5821f481deceef114da892e.2592000.1467287744.282335-7519663"      os.system('mpg123 "%s"'%(url))      print "wait..1s"      time.sleep(1)

原创文章,转载请注明: 转载自URl-team

本文链接地址: 树莓派 python 百度语音控制 gpio 控制开关灯

  1. 学习—用 Python 和 OpenCV 检测和跟踪运动对象
  2. 使用pyaiml机器人模块快速做个和你智能对话的大脑
  3. python-opencv人脸识别与树莓派摄像头转头跟随()
  4. face++人脸识别与人脸库匹配python实现笔记一
  5. 让树莓派开机运行Python脚本
  6. python_face++ 上传本地图片进行解析