一、所需库安装

pip install pyaudio
pip install speechrecognition
pip install baidu-aip
pip install wave
pip install wheel
pip install pyinstaller

二、百度官网申请服务

三、源代码分享

import pyaudio
import wave
from aip import aipspeech
import time




# 用pyaudio库录制音频
#  out_file:输出音频文件名
#  rec_time:音频录制时间(秒)
def audio_record(out_file, rec_time):
  chunk = 1024
  format = pyaudio.paint16 # 16bit编码格式
  channels = 1 # 单声道
  rate = 16000 # 16000采样频率

  p = pyaudio.pyaudio()
  # 创建音频流
  stream = p.open(format=format, # 音频流wav格式
          channels=channels, # 单声道
          rate=rate, # 采样率16000
          input=true,
          frames_per_buffer=chunk)

  print("开始记录语音{0}秒后开始识别...".format(rec_time))

  frames = [] # 录制的音频流
  # 录制音频数据
  for i in range(0, int(rate / chunk * rec_time)):
    data = stream.read(chunk)
    frames.append(data)

  # 录制完成
  stream.stop_stream()
  stream.close()
  p.terminate()

  print("结束识别")

  # 保存音频文件
  wf = wave.open(out_file, 'wb')
  wf.setnchannels(channels)
  wf.setsampwidth(p.get_sample_size(format))
  wf.setframerate(rate)
  wf.writeframes(b''.join(frames))
  wf.close()


def audio_recog(recogfile):
  # 读取文件
  def get_file_content(filepath):
    with open(filepath, 'rb') as fp:
      return fp.read()


  # 识别本地文件
  result = client.asr(get_file_content(recogfile), 'wav', 16000, {'dev_pid': 1537,})
  return result

def write_file(file,text):
  import time
  time = time.strftime("%y-%m-%d %h:%m:%s", time.localtime())
  f = open(file, 'a')
  f.write(time+':'+text+'\n')
  f.close()

audiofile="audio.wav"
textfile="识别结果.txt"

""" 你的 appid ak sk """
app_id = '你的app_id'
api_key = '你的api_key'
secret_key = '你的secret_key'

client = aipspeech(app_id, api_key, secret_key)


if __name__ == '__main__':
  while true:
    audio_record(audiofile, 5)
    textresult = audio_recog("audio.wav")
    if textresult['err_msg'] =="success.":
      print(textresult['result'])
      write_file(textfile,str(textresult['result']))

四、打包成软件

进入到目录执行下面命令:

pyinstaller -f main.py

到此这篇关于python结合百度语音识别实现实时翻译软件的实现的文章就介绍到这了,更多相关python 实时翻译软件内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!