python语音对话
安装相关库:pyaudio、AipSpeech、pyttsx3、urllib、requests。
pip install …
手动添加镜像源:
pip install package_name -i http://mirrors.aliyun.com/pypi/simple/
pip命令设置镜像源:
当前用户文件夹下创建pip文件夹,其中添加pip.ini文件。
pip.ini文件内容:
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
设置完成后pip命令自动从配置的镜像源安装。
1. 接收语音输入。
Speak.py
import time
import wave
from pyaudio import PyAudio, paInt16
framerate = 16000 # 采样率
num_samples = 2000 # 采样点
channels = 1 # 声道
samplewidth = 2 # 采样宽度
filepath = 'voices/myvoice.wav'
class Speak():
def save_wave_file(self, filepath, data):
wave_open = wave.open(filepath, 'wb')
wave_open.setnchannels(channels)
wave_open.setsampwidth(samplewidth)
wave_open.setframerate(framerate)
wave_open.writeframes(b''.join(data))
wave_open.close()
# 接收语音输入
def record(self):
audio = PyAudio()
stream = audio.open(format=paInt16, channels=channels, rate=framerate, input=True,
frames_per_buffer=num_samples)
buf = []
t = time.time()
print("正在说话...")
while time.time() < t + 5:
audio_data = stream.read(num_samples)
buf.append(audio_data)
print("结束说话")
self.save_wave_file(filepath, buf)
stream.close()
在路径下的voices目录下生成wav格式文件。
2. 语音识别。
ReadWav.py
from aip import AipSpeech
# app info
APP_ID = '27017392'
APP_KEY = 'HfVYutlUKqYKIGloczfQzVm1'
SECRET_KEY = 'oc4rlYpWKZETosbz7HFF8u2QuAVRkqDz'
client = AipSpeech(APP_ID, APP_KEY, SECRET_KEY)
class ReadWav():
def get_file_content(self, filepath):
with open(filepath, 'rb') as r:
return r.read()
def predict(self):
# 识别
return client.asr(self.get_file_content('voices/myvoice.wav'), 'wav', '16000', {'dev_pid': 1537})
3. 语音机器人。
Robot.py
import pyttsx3
class Robot():
def __init__(self):
self.engine = pyttsx3.init()
self.rate = self.engine.getProperty('rate')
self.engine.setProperty('rate', self.rate - 50)
def say(self, msg):
self.engine.say(msg)
self.engine.runAndWait()
4. 主程序。
Main.py
import urllib.parse
import requests
from Speak import Speak
from ReadWav import ReadWav
from Robot import Robot
def talking(msg):
url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=%s' % urllib.parse.quote(msg)
resp = requests.get(url)
return resp.json().get('content')
speak = Speak()
wav = ReadWav()
robot = Robot()
while True:
speak.record()
text = wav.predict().get('result')[0]
print('本人说:' + text)
content = talking(text)
print("对方回答:" + content)
robot.say(content)
智能聊天Api接口:http://api.qingyunke.com/
常用镜像源:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/