python语音播放文本_使用Watson for Python连续实时语音转文本

importasyncioimportwebsocketsimportjsonimportrequestsimportpyaudioimporttime# Variables to use for recording audioCHUNK=1024FORMAT=pyaudio.paInt16

CHANNELS=2RATE=16000p=pyaudio.PyAudio()# This is the language model to use to transcribe the audiomodel="en-US_BroadbandModel"# These are the urls we will be using to communicate with Watsondefault_url="https://stream.watsonplatform.net/speech-to-text/api"token_url="https://stream.watsonplatform.net/authorization/api/v1/token?"\"url=https://stream.watsonplatform.net/speech-to-text/api"url="wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?model=en-US_BroadbandModel"# BlueMix app credentialsusername=""# Your Bluemix App usernamepassword=""# Your Bluemix App password# Send a request to get an authorization keyr=requests.get(token_url,auth=(username,password))auth_token=r.text

token_header={"X-Watson-Authorization-Token":auth_token}# Params to use for Watson APIparams={"word_confidence":True,"content_type":"audio/l16;rate=16000;channels=2","action":"start","interim_results":True}# Opens the stream to start recording from the default microphonestream=p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,output=True,frames_per_buffer=CHUNK)asyncdefsend_audio(ws):# Starts recording of microphoneprint("* READY *")start=time.time()whileTrue:try:print(".")data=stream.read(CHUNK)await ws.send(data)iftime.time()-start>20:# Records for n secondsawait ws.send(json.dumps({'action':'stop'}))returnFalseexceptExceptionase:print(e)returnFalse# Stop the stream and terminate the recordingstream.stop_stream()stream.close()p.terminate()asyncdefspeech_to_text():asyncwithwebsockets.connect(url,extra_headers=token_header)asconn:# Send request to watson and waits for the listening responsesend=await conn.send(json.dumps(params))rec=await conn.recv()print(rec)asyncio.ensure_future(send_audio(conn))# Keeps receiving transcript until we have the final transcriptwhileTrue:try:rec=await conn.recv()parsed=json.loads(rec)transcript=parsed["results"][0]["alternatives"][0]["transcript"]print(transcript)#print(parsed)if"results"inparsed:iflen(parsed["results"])>0:if"final"inparsed["results"][0]:ifparsed["results"][0]["final"]:#conn.close()#return FalsepassexceptKeyError:conn.close()returnFalse# Starts the application looploop=asyncio.get_event_loop()loop.run_until_complete(speech_to_text())loop.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值