讯飞实时语音转写 python3.6.1 可完美运行 解析返回的json字符串 输出所获语音文字

百度语音识别对录音要求较高(可能是我的问题,sdk和在线api都试过了(滑稽保命)),失败后选择讯飞语音,官方提供的文档是python2版本的 ,经过修改后可在python3中运行 ,解析返回的json字符串 最后输出语音文字
一、登陆讯飞官网申请应用
在这里插入图片描述
二选择实时语音转写并开通服务
在这里插入图片描述
三、代码如下
(只是修改讯飞官网给出的demo,在python3环境下能运行。这里的音频是官网给出的音频)

#-*- encoding:utf-8 -*-
#2020/2/19   修改人员:monster water


import sys
import hashlib
from hashlib import sha1
import hmac
import base64
from socket import *
import json, time, threading
from websocket import create_connection
import websocket
from urllib.parse import quote
import logging
import importlib
importlib.reload(sys)
#sys.setdefaultencoding("utf8")
logging.basicConfig()

base_url = "ws://rtasr.xfyun.cn/v1/ws"
app_id = "5e4baasdasaabifba83"                                                      #控制台应用里得到   注意是实时语音转写
api_key = "zxcafhaiufgiabf"                               # 同上
file_path = "test_1.pcm"                                                    #语音文件名 修改成自己的注意路径

end_tag = "{\"end\": true}"

class Client():
    def __init__(self):
        # 生成鉴权参数
        ts = str(int (time.time()))
        tmp = app_id + ts
        hl = hashlib.md5()
        hl.update(tmp.encode(encoding='utf-8'))
        h2=hl.hexdigest()
        apikey=(bytes(api_key.encode('utf-8')))
        h2=h2.encode('utf-8')
        my_sign = hmac.new(apikey, h2, sha1).digest()
        #signa = base64.b64encode(bytes(my_sign.encode('utf-8')))
        signa = base64.b64encode(my_sign).decode('utf-8')
        self.ws = create_connection(base_url + "?appid=" + app_id + "&ts=" + ts + "&signa=" + quote(signa))
        self.trecv = threading.Thread(target=self.recv)
        self.trecv.start()

    def send(self, file_path):
        file_object = open(file_path, 'rb')
        try:
            index = 1
            while True:
                chunk = file_object.read(1280)
                if not chunk:
                    break
                self.ws.send(bytes(chunk))

                index += 1
                time.sleep(0.04)
        finally:
            # print str(index) + ", read len:" + str(len(chunk)) + ", file tell:" + str(file_object.tell())
            file_object.close()

        self.ws.send(bytes(end_tag.encode('utf-8')))
        print ("send end tag success")

    def recv(self):
        try:
            while self.ws.connected:
                result = str(self.ws.recv())
                if len(result) == 0:
                    print ("receive result end")
                    break
                result_dict = json.loads(result)

                # 解析结果
                if result_dict["action"] == "started":
                    print ("handshake success, result: " + result)

                if result_dict["action"] == "result":
                    #print ("rtasr result: " + result)
                    #print (result_dict['data'])
                    result1=json.loads(result_dict['data']) #以下部分为把获得的json文件 解析
                    result2=result1['cn']['st']['rt'][0]['ws']
                    #print (result2)
                    len1=len(result1['cn']['st']['rt'][0]['ws'])
                    # result2 = json.loads(result1['cn']['st'])
                    # print (result2)
                    str1=[]
                    for item in range(len1):
                        # result3=result2[item]['cw'][0]['w']
                        # print (result3)
                        result3=result2[item]['cw'][0]['w']
                        str1.append(result3)
                    s=''.join(str1)
                    print(s)                           #输出最后得到的字符串


                if result_dict["action"] == "error":
                    print ("rtasr error: " + result)
                    self.ws.close()
                    return
        except websocket.WebSocketConnectionClosedException:
            print ("receive result end")

    def close(self):
        self.ws.close()
        print ("connection closed")

if __name__ == '__main__':
    client = Client()
    client.send(file_path)

四、运行结果
在这里插入图片描述下面是自己测试:
在这里插入图片描述 成功

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
是一家提供语音识别和自然语言处理技术的公司,它的实时语音转写功能可以将语音实时转化为文本。使用实时语音转写需要以下步骤: 第一步,创建开放平台账号并在平台上申请相应的应用ID和secret key。 第二步,安装Python SDK并导入依赖包,例如:requests、json。 第三步,通过实时语音转写接口发送请求,传递相关参数,从而获得转写结果。 下面是一个基于Python SDK开发的实时语音转写示例代码: ```python # 导入依赖包 import websocket import requests import time import hashlib import base64 import json # API身份验证 APPID = '你的应用ID' API_SECRET = '你的APISecret' API_KEY = '你的APIKey' # 获取时间戳和鉴权参数 def getHeaderParam(): curTime = str(int(time.time())) param = { "engine_type": "sms16k", "aue": "raw", "sample_rate": "16000", "param": "aue=raw,engine_type=sms16k,sample_rate=16000" } paramStr = json.dumps(param) paramBase64 = str(base64.b64encode(paramStr.encode('utf-8')), 'utf-8') checkSum = hashlib.md5((API_KEY + curTime + paramBase64).encode('utf-8')).hexdigest() header = { 'X-CurTime':curTime, 'X-Param':paramBase64, 'X-Appid':APPID, 'X-CheckSum':checkSum } return header # 处理结果 def on_message(ws, message): messageDict = json.loads(message) code = messageDict['code'] if code != 0: print("请重新开始录音") else: result = messageDict['data']['result'] print(result) # 主函数 if __name__ == '__main__': # 通过REST API获取实时语音转写WebSocket地址和token response = requests.post('http://api.xfyun.cn/v1/service/v1/iat', headers=getHeaderParam()) responseDict = json.loads(response.text) if responseDict['code'] != '0': print(responseDict['message']) else: address = responseDict['data']['url'] token = responseDict['data']['token'] # 创建WebSocket连接 ws = websocket.WebSocketApp(address, on_message=on_message, on_error=on_error, on_close=on_close) # 添加鉴权信息 ws.headers = { 'Authorization': token } # 开始录音 ws.send(json.dumps({'common': {'app_id': APPID}})) ws.send(json.dumps({'business': {'language': 'zh_cn','domain': 'iat','accent': 'mandarin','vad_eos': 10000},'data': {'status': 0}})) # 持续录音并发送转写请求 while(True): audio = input("请输入:") # 实现语音输入(如需使用麦克风录音?) if audio == '': break else: ws.send(audio.encode("utf-8")) # 结束录音 ws.send(json.dumps({'business': {'cmd': 'auw', 'aus': '00'}})) ws.close() ``` 注意,该示例代码采用的是模拟语音输入的方式,可以通过实现语音输入并将其转为byte字符串的方式替换。另外,在处理结果的函数内应该添加一些错误处理,以防出现意外情况。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值