參考鏈接:https://blog.csdn.net/qazwyc/article/details/57153734
本文所有代碼鏈接:https://pan.baidu.com/s/1LT5LBkOOGrzMyg6GADf-Og
開頭沒有加入強制編碼三句:
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
導致我吃了不少苦,用python2.7運行會出現各種錯誤,所得到結果需要編碼轉換,雖然實現了,可是感覺不舒服,因沒法顯示漢字啊,加了上面三句可以的,我樹莓派是裝過漢字系統的。
用python3.5打開時如上圖,如果點了OK,那就麻煩了,文件就廢掉了!所以如果編輯,要用記事本打開。
樹莓派中文件位置如下:
運行過程如下:
一. 沒有加以上三句編碼 完成的任務代碼如下(無法顯示漢字,請用記事本打開編輯):
#!/usr/bin/env python
import wave
import requests
import time
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
import os
import signal
import RPi.GPIO as GPIO
#! BOARD編號方式,基於插座引腳編號
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
framerate = 16000 # 採樣率
num_samples = 2000 # 採樣點
channels = 1 # 聲道
sampwidth = 2 # 採樣寬度2bytes
FILEPATH = ‘speech.wav’
base_url = “https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s”
APIKey = “bn58jNgdjRED0uKCScW9R2C6”
SecretKey = “LgLYImS2Hcxqno6QQzIMrH7Gf8uRRbZb”
HOST = base_url % (APIKey, SecretKey)
def getToken(host):
res = requests.post(host)
return res.json()[‘access_token’]
def save_wave_file(filepath, data):
wf = wave.open(filepath, ‘wb’)
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b’’.join(data))
wf.close()
def my_record():
pa = PyAudio()
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
# count = 0
t = time.time()
print(‘record…’)
while time.time() < t + 4: # second
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('record over.')
save_wave_file(FILEPATH, my_buf)
stream.close()
def get_audio(file):
with open(file, ‘rb’) as f:
data = f.read()
return data
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = ‘wav’
RATE = ‘16000’
CHANNEL = 1
CUID = ‘*******’
SPEECH = base64.b64encode(speech_data).decode(‘utf-8’)
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid':dev_pid
}
url = 'https://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('recognizing...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
print 'get nothing!'
def sigint_handler(signum, frame):
stream.stop_stream()
stream.close()
p.terminate()
GPIO.cleanup()
print ‘catched interrupt signal!’
sys.exit(0)
if name == ‘main’:
flag = ‘y’
# 註冊ctrl-c中斷
signal.signal(signal.SIGINT, sigint_handler)
while flag.lower() == 'y':
my_record()
TOKEN = getToken(HOST)
speech = get_audio(FILEPATH)
words = speech2text(speech, TOKEN)#默認1537
print(words)
result = words.encode('gbk') # gbk編碼,此編碼也可用於指定網頁的打開,但對於百度自動搜索會出亂碼
if ('開燈') in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
print 'turn on light'
elif ('亮紅燈') in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print 'red light'
elif ('關燈') in result:
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print 'turn off light'
elif ('放首歌') in result:
print 'you mei you na me yi shou ge!'
os.system('mplayer song.mp3')
else:
print 'please say words in: kai deng, liang hong deng, guan deng, fang shou ge'
flag = raw_input('Continue?(y/n):\n')#python3用input()
GPIO.cleanup()
二. 加了強制編碼三句,結合圖靈機器人,完成任務的如下(可控制燈,可播放本地音樂,可跟機器人聊天,顯示漢字):
#!/usr/bin/env python
import wave
import requests
import time
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
import os
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
import signal
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
framerate = 16000 # 採樣率
num_samples = 2000 # 採樣點
channels = 1 # 聲道
sampwidth = 2 # 採樣寬度2bytes
FILEPATH = ‘speech.wav’
base_url = “https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s”
APIKey = “bn58jNgdjRED0uKCScW9R2C6”
SecretKey = “LgLYImS2Hcxqno6QQzIMrH7Gf8uRRbZb”
HOST = base_url % (APIKey, SecretKey)
def getToken(host):
res = requests.post(host)
return res.json()[‘access_token’]
def save_wave_file(filepath, data):
wf = wave.open(filepath, ‘wb’)
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b’’.join(data))
wf.close()
def my_record():
pa = PyAudio()
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
# count = 0
t = time.time()
print(‘record…’)
while time.time() < t + 4: # second
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('record over.')
save_wave_file(FILEPATH, my_buf)
stream.close()
def get_audio(file):
with open(file, ‘rb’) as f:
data = f.read()
return data
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = ‘wav’
RATE = ‘16000’
CHANNEL = 1
CUID = ‘*******’
SPEECH = base64.b64encode(speech_data).decode(‘utf-8’)
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid':dev_pid
}
url = 'https://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('recognizing...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
print 'get nothing!'
def sigint_handler(signum, frame):
stream.stop_stream()
stream.close()
p.terminate()
GPIO.cleanup()
print ‘catched interrupt signal!’
sys.exit(0)
if name == ‘main’:
flag = ‘y’
# 註冊ctrl-c中斷
signal.signal(signal.SIGINT, sigint_handler)
while flag.lower() == ‘y’:
print(‘請在以下內容中選說:開燈,亮紅燈,關燈,放首歌,英文歌’)
my_record()
TOKEN = getToken(HOST)
speech = get_audio(FILEPATH)
result = speech2text(speech, TOKEN)#默認1537
print(result)
if (‘開燈’) in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
print ‘turn on light’
elif ('亮紅燈') in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print 'red light'
elif ('關燈') in result:
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print 'turn off light'
elif ('放首歌') in result:
print '周華健的有沒有那麼一首歌'
os.system('mplayer song.mp3')
elif ('英文歌') in result:
print 'Carpenters - Yesterday Once More'
os.system('mplayer yesterday.mp3')
else:
print '圖靈機器人接管服務'
flag = raw_input('Continue?(y/n):\n')#python3用input()
GPIO.cleanup()
三. 因爲圖靈機器人接收和返回的都是文字,所以以上版本的返回(除了音樂)都是文字,把文字快速在本地轉成聲音並播放(不用百度語音合成,因語音合成很成熟很簡單,百度合成還需要再上網,慢)代碼如下:
#!/usr/bin/env python
import wave
import requests
import time
import urllib
import json
import base64
from pyaudio import PyAudio, paInt16
import webbrowser
import os
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8’)
import signal
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
framerate = 16000 # 採樣率
num_samples = 2000 # 採樣點
channels = 1 # 聲道
sampwidth = 2 # 採樣寬度2bytes
FILEPATH = ‘speech.wav’
base_url = “https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s”
APIKey = “bn58jNgdjRED0uKCScW9R2C6”
SecretKey = “LgLYImS2Hcxqno6QQzIMrH7Gf8uRRbZb”
HOST = base_url % (APIKey, SecretKey)
def getToken(host):
res = requests.post(host)
return res.json()[‘access_token’]
def save_wave_file(filepath, data):
wf = wave.open(filepath, ‘wb’)
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b’’.join(data))
wf.close()
def my_record():
pa = PyAudio()
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
# count = 0
t = time.time()
print(‘record…’)
while time.time() < t + 4: # second
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('record over.')
save_wave_file(FILEPATH, my_buf)
stream.close()
def get_audio(file):
with open(file, ‘rb’) as f:
data = f.read()
return data
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = ‘wav’
RATE = ‘16000’
CHANNEL = 1
CUID = ‘*******’
SPEECH = base64.b64encode(speech_data).decode(‘utf-8’)
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid':dev_pid
}
url = 'https://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('recognizing...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
print 'get nothing!'
def sigint_handler(signum, frame):
stream.stop_stream()
stream.close()
p.terminate()
GPIO.cleanup()
print ‘catched interrupt signal!’
sys.exit(0)
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
key = ‘05ba411481c8cfa61b91124ef7389767’
api = ‘http://www.tuling123.com/openapi/api?key=’ + key + ‘&info=’
if name == ‘main’:
flag = ‘y’
# 註冊ctrl-c中斷
signal.signal(signal.SIGINT, sigint_handler)
while flag.lower() == ‘y’:
print(‘請在以下內容中選說:開燈,亮紅燈,關燈,放首歌,英文歌’)
my_record()
TOKEN = getToken(HOST)
speech = get_audio(FILEPATH)
result = speech2text(speech, TOKEN)#默認1537
print(result)
if (‘開燈’) in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
print ‘turn on light’
elif (‘亮紅燈’) in result:
GPIO.output(11, GPIO.HIGH)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print ‘red light’
elif (‘關燈’) in result:
GPIO.output(11, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
print ‘turn off light’
elif (‘放首歌’) in result:
print ‘周華健的有沒有那麼一首歌’
os.system(‘mplayer song.mp3’)
elif (‘英文歌’) in result:
print ‘Carpenters - Yesterday Once More’
os.system(‘mplayer yesterday.mp3’)
else:
print ‘圖靈機器人接管服務’
request = api + str(result)
response = getHtml(request)
dic_json = json.loads(response)
print '機器人: '.decode(‘utf-8’) + dic_json[‘text’]
a = dic_json[‘text’]
print type(a)
# 將a的文本存入3.txt
f=open(“Voicecontrol3.txt”,‘w’)
f.truncate()
f.write(a)
f.close()
# 通過ekho語音合成爲3.wav並播放
os.system(‘ekho -f Voicecontrol3.txt -o Voicecontrol3.wav’)
os.system(‘mplayer Voicecontrol3.wav’)
flag = raw_input(‘Continue?(y/n):\n’)#python3用input()
GPIO.cleanup()