当前位置: 移动技术网 > IT编程>脚本编程>Python > python调用百度语音REST API

python调用百度语音REST API

2018年09月23日  | 移动技术网IT编程  | 我要评论

洪荒神医txt下载,黄家驹哪年死的,天际浩劫2之未来战争

本文实例为大家分享了python调用百度语音rest api的具体代码,供大家参考,具体内容如下

(百度的rest接口的部分网址发生了一定的变化,相关代码已更新)

百度通过 rest api 的方式给开发者提供一个通用的 http 接口,基于该接口,开发者可以轻松的获得语音合成与语音识别能力。sdk中只提供了php、c和java的相关样例,使用python也可以灵活的对端口进行调用,本文描述了简单使用python调用百度语音识别服务 rest api 的简单样例。

1、语音识别与语音合成的调用

注册开发者帐号和创建应用的过程就不再赘述,百度的rest api在调用过程基本分为三步:

  • 获取token
  • 向rest接口提交数据
  • 处理返回数据

具体代码如下所示:

#!/usr/bin/python3

import urllib.request
import urllib
import json
import base64
class baidurest:
  def __init__(self, cu_id, api_key, api_secert):
    # token认证的url
    self.token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
    # 语音合成的resturl
    self.getvoice_url = "http://tsn.baidu.com/text2audio?tex=%s&lan=zh&cuid=%s&ctp=1&tok=%s"
    # 语音识别的resturl
    self.upvoice_url = 'http://vop.baidu.com/server_api'

    self.cu_id = cu_id
    self.gettoken(api_key, api_secert)
    return

  def gettoken(self, api_key, api_secert):
    # 1.获取token
    token_url = self.token_url % (api_key,api_secert)

    r_str = urllib.request.urlopen(token_url).read()
    token_data = json.loads(r_str)
    self.token_str = token_data['access_token']
    pass

  def getvoice(self, text, filename):
    # 2. 向rest接口提交数据
    get_url = self.getvoice_url % (urllib.parse.quote(text), self.cu_id, self.token_str)

    voice_data = urllib.request.urlopen(get_url).read()
    # 3.处理返回数据
    voice_fp = open(filename,'wb+')
    voice_fp.write(voice_data)
    voice_fp.close()
    pass

  def gettext(self, filename):
    # 2. 向rest接口提交数据
    data = {}
    # 语音的一些参数
    data['format'] = 'wav'
    data['rate'] = 8000
    data['channel'] = 1
    data['cuid'] = self.cu_id
    data['token'] = self.token_str
    wav_fp = open(filename,'rb')
    voice_data = wav_fp.read()
    data['len'] = len(voice_data)
    data['speech'] = base64.b64encode(voice_data).decode('utf-8')
    post_data = json.dumps(data)
    r_data = urllib.request.urlopen(self.upvoice_url,data=bytes(post_data,encoding="utf-8")).read()
    # 3.处理返回数据
    return json.loads(r_data)['result']

if __name__ == "__main__":
  # 我的api_key,供大家测试用,在实际工程中请换成自己申请的应用的key和secert
  api_key = "srhykqzl3se1urnaeuz0fkdt" 
  api_secert = "hgqeckampb0elmqtrgc2vjwdmjo7t89d"
  # 初始化
  bdr = baidurest("test_python", api_key, api_secert)
  # 将字符串语音合成并保存为out.mp3
  bdr.getvoice("你好北京邮电大学!", "out.mp3")
  # 识别test.wav语音内容并显示
  print(bdr.gettext("out.wav"))

2、调用pyaudio使用麦克风录制声音

python中的pyaudio库可以直接通过麦克风录制声音,可使用pip进行安装。我们可以通过调用该库,获取到wav测试语音。
具体代码如下所示:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from pyaudio import pyaudio, paint16 
import numpy as np 
from datetime import datetime 
import wave

class recoder:
  num_samples = 2000   #pyaudio内置缓冲大小
  sampling_rate = 8000  #取样频率
  level = 500     #声音保存的阈值
  count_num = 20   #num_samples个取样之内出现count_num个大于level的取样则记录声音
  save_length = 8     #声音记录的最小长度:save_length * num_samples 个取样
  time_count = 60   #录音时间,单位s

  voice_string = []

  def savewav(self,filename):
    wf = wave.open(filename, 'wb') 
    wf.setnchannels(1) 
    wf.setsampwidth(2) 
    wf.setframerate(self.sampling_rate) 
    wf.writeframes(np.array(self.voice_string).tostring()) 
    # wf.writeframes(self.voice_string.decode())
    wf.close() 

  def recoder(self):
    pa = pyaudio() 
    stream = pa.open(format=paint16, channels=1, rate=self.sampling_rate, input=true, 
      frames_per_buffer=self.num_samples) 
    save_count = 0 
    save_buffer = [] 
    time_count = self.time_count

    while true:
      time_count -= 1
      # print time_count
      # 读入num_samples个取样
      string_audio_data = stream.read(self.num_samples) 
      # 将读入的数据转换为数组
      audio_data = np.fromstring(string_audio_data, dtype=np.short)
      # 计算大于level的取样的个数
      large_sample_count = np.sum( audio_data > self.level )
      print(np.max(audio_data))
      # 如果个数大于count_num,则至少保存save_length个块
      if large_sample_count > self.count_num:
        save_count = self.save_length 
      else: 
        save_count -= 1

      if save_count < 0:
        save_count = 0 

      if save_count > 0 : 
      # 将要保存的数据存放到save_buffer中
        #print save_count > 0 and time_count >0
        save_buffer.append( string_audio_data ) 
      else: 
      #print save_buffer
      # 将save_buffer中的数据写入wav文件,wav文件的文件名是保存的时刻
        #print "debug"
        if len(save_buffer) > 0 : 
          self.voice_string = save_buffer
          save_buffer = [] 
          print("recode a piece of voice successfully!")
          return true
      if time_count==0: 
        if len(save_buffer)>0:
          self.voice_string = save_buffer
          save_buffer = [] 
          print("recode a piece of voice successfully!")
          return true
        else:
          return false

if __name__ == "__main__":
  r = recoder()
  r.recoder()
  r.savewav("test.wav")  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网