python 实现语音聊天机器人的示例代码
作者:氢立方 发布时间:2021-03-24 14:36:07
标签:python,语音聊天,机器人
前言
在不远的将来,实现一定程度上的语音支持将成为日常科技的基本要求,整合了语音识别的python程序提供了其他技术无法比拟的交互性和可访问性。最重要的是,在python程序中实现语音识别非常简单。整个代码实现下来还不到150行。
原理简介
许多现代语音识别系统会在HMM识别之前使用神经网络,通过特征变换和降维技术来简化语音信号,也可以使用语音活动检测器将音频信号减少到可能包含语音的部分。
幸运的是,对于python来讲,一些语音识别的服务可通过API在线使用,且其中大部分也提供了Python SDK。
本文做的聊天机器人是基于百度语音识别和图灵机器人二者之上共同实现的。大致的流程如下图:
原理流程图.PNG
这里需要用的模块库有 requests、time、datetime、pyaudio、wave、aipspeech 等。
话不多说,上代码:
##@氢立方 2018.0911
import requests
import time
import pygame
from datetime import datetime
from aip import AipSpeech
from pyaudio import PyAudio,paInt16
import wave
import os
framerate=8000
NUM_SAMPLES=2000
channels=1
sampwidth=2
TIME=2
def save_wave_file(filename,data):
'''save the date to the wavfile'''
wf=wave.open(filename,'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=1,
rate=framerate,input=True,
frames_per_buffer=NUM_SAMPLES)
my_buf=[]
count=0
while count<TIME*6:#控制录音时间
string_audio_data = stream.read(NUM_SAMPLES)
my_buf.append(string_audio_data)
count+=1
print('.')
save_wave_file('0001.wav',my_buf)
stream.close()
##def play():
## wf=wave.open(r"D:/41125.mp3",'rb')
## p=PyAudio()
## stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=
## wf.getnchannels(),rate=wf.getframerate(),output=True)
## while True:
## data=wf.readframes(chunk)
## if data=="":break
## stream.write(data)
## stream.close()
## p.terminate()
##
这里大家需要改成自己的ID和KEY
APP_ID = '11****843'
API_KEY = '3Mnv***8**88******GbXa'
SECRET_KEY = '147***8*88****1227684'
aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def getText(url):
text = requests.post(url).json()
return text['text']
##
##key = '6ddc57c5761a4c62a30ea840e5ae163f'
#api = 'http://www.tuling123.com/openapi/api?key=' + key +'&info ='
key = '8b005db5f57556fb96dfd98fbccfab84'
api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='
##
while True:
## info = input("我说\n")
## chunk=2014
my_record()
print("录音完成")
def get_file_content(filePath):
with open(filePath,'rb') as fp:
return fp.read()
a = aipSpeech.asr(get_file_content('0001.wav '),'wav',8000,{})
print(a)
b = str(a['result'])
info = b
url = api + info
#print(url)
text_01 = getText(url)
print("机器人回\n",text_01)
now = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")
filename_01 = now + ".mp3"
result = aipSpeech.synthesis( text_01,'zh',1,{'vol': 5,'per' : 2} )
if not isinstance(result, dict):
with open(filename_01, 'wb') as f:
f.write(result)
print("--------------------------------------")
time.sleep(1)
pygame.mixer.init()
print("语音1")
file= filename_01
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(15)
pygame.mixer.music.stop()
pygame.quit()
运行结果如下:
小编说的是:今天看了电视剧。机器人回复的是:看了有没有开心点
在某种意义上来说,语境还是符合常理的。
来源:https://www.jianshu.com/p/16a226ca8139


猜你喜欢
- 有序字典-OrderedDict简介示例有序字典和通常字典类似,只是它可以记录元素插入其中的顺序,而一般字典是会以任意的顺序迭代的。参见下面
- ARIMA模型预测餐厅销量import numpy as npimport pandas as pdimport matplotlib.py
- 直接开始,过程中对每一步可能出现的错误都进行了说明。1、安装好xampp,然后打开终端,输入:mysql -u root -p成功进入了,擦
- 我就废话不多说了,直接上代码吧!import Imagefrom datetime import datetimeimport osstr
- 强大的group by 代码如下:select stdname, isnull(sum( case stdsubject whe
- 1.什么是FBV和CBVFBV是指视图函数以普通函数的形式;CBV是指视图函数以类的方式。2.普通FBV形式def index(reques
- mysql数据库没有增量备份的机制,当数据量太大的时候备份是一个很大的问题。还好mysql数据库提供了一种主从备份的机制,其实就是把主数据库
- vue项目依赖升级报错处理1.Vue Router 升级到3.5.1报错:Navigation cancelled from "/
- 今天学习php,当然是要先安装好运行环境了,phpstyudy是一个运行php的集成环境, 一键安装对新手很友好,与时作为一个新手,便跟着教
- Exec 是 os 包中的一个子包,它可用于使用 Go 运行外部命令。Go exec 命令教程展示了如何在 Golang 中执行 shell
- Sun周三宣布,准备以10亿美元收购MySQL开源数据库公司。据悉,Sun将支付大约8亿美元现金给MySQL,以获得其私募股票,另外,Sun
- web框架是什么?web开发框架是一组工具,同时也提供了非常多的资源,供软件开发人员构建和管理网站、提供web服务、编写web应用程序。它是
- 代码如下:--新增表字段 ALTER procedure [dbo].[sp_Web_TableFiled_Insert] (
- 本篇阅读的代码片段来自于30-seconds-of-python。1、average_bydef average_by(lst, fn=la
- 共轭转置共轭转置The symbols (·)T , (·)∗, and (·)H are,respectively, the transp
- atom(一款开源的代码编辑器)是github专门为程序员推出的一个跨平台文本编辑器。具有简洁和直观的图形用户界面,并有很多有趣的特点:支持
- 前言事务隔离级别的实现原理:简单来说就是各种锁机制和MVCC多版本并发控制我们学习知识的时候,需要了解知识点出现的原因,什么情况下能用到这个
- 首先来看一个例子,正常情况下我们定义并且实例一个类如下class Foo(object):def __init__(self):  
- 问题:<!DOCTYPE html><html lang="en"><head> &
- 实例1、取得MYSQL版本# -*- coding: UTF-8 -*-#安装MYSQL DB for pythonimport MySQL