樹莓派 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++ 上傳本地圖片進行解析