python监听麦克风并调用阿里云的实时语音转文字

import time
import threading
import queue
import sounddevice as sd
import numpy as np
import nls
import sys

# 阿里云配置信息
URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
TOKEN = "016ca1620aff421da8fac81b9fb52dc5"  # 参考https://help.aliyun.com/document_detail/450255.html获取token
APPKEY = "ahS8ZDaimkpWALHi"  # 获取Appkey请前往控制台:https://nls-portal.console.aliyun.com/applist


# Queue to hold the recorded audio data
audio_queue = queue.Queue()

# Callback function to capture audio data
def audio_callback(indata, frames, time, status):
    if status:
        print(status, file=sys.stderr)
    audio_queue.put(indata.copy())

class RealTimeSpeechRecognizer:
    def __init__(self, url, token, appkey):
        self.url = url
        self.token = token
        self.appkey = appkey
        self.transcriber = None
        self.__initialize_transcriber()

    def __initialize_transcriber(self):
        self.transcriber = nls.NlsSpeechTranscriber(
            url=self.url,
            token=self.token,
            appkey=self.appkey,
            on_sentence_begin=self.on_sentence_begin,
            on_sentence_end=self.on_sentence_end,
            on_start=self.on_start,
            on_result_changed=self.on_result_changed,
            on_completed=self.on_completed,
            on_error=self.on_error,
            on_close=self.on_close,
            callback_args=[self]
        )
        self.transcriber.start(aformat="pcm", enable_intermediate_result=True,
                               enable_punctuation_prediction=True, enable_inverse_text_normalization=True)

    def send_audio(self, audio_data):
        if self.transcriber:
            self.transcriber.send_audio(audio_data)

    def stop_transcription(self):
        if self.transcriber:
            self.transcriber.stop()

    def on_sentence_begin(self, message, *args):
        print("Sentence begin: {}".format(message))

    def on_sentence_end(self, message, *args):
        print("Sentence end: {}".format(message))

    def on_start(self, message, *args):
        print("Start: {}".format(message))

    def on_result_changed(self, message, *args):
        print("Result changed: {}".format(message))

    def on_completed(self, message, *args):
        print("Completed: {}".format(message))

    def on_error(self, message, *args):
        print("Error: {}".format(message))

    def on_close(self, *args):
        print("Closed: {}".format(args))

# 调用阿里云的语音转文字的接口
def recognize_speech(audio_data, recognizer):
    audio_data = np.concatenate(audio_data)
    recognizer.send_audio(audio_data.tobytes())

# Start the audio stream and process audio data
def start_audio_stream(recognizer):
    with sd.InputStream(callback=audio_callback, channels=1, samplerate=16000, dtype='int16'):
        print("Recording audio... Press Ctrl+C to stop.")
        audio_buffer = []
        try:
            while True:
                while not audio_queue.empty():
                    audio_buffer.append(audio_queue.get())
                if len(audio_buffer) >= 10:  # 调整音频数据块大小
                    audio_data = np.concatenate(audio_buffer)
                    recognize_speech(audio_data, recognizer)
                    audio_buffer = []  # Clear buffer after sending
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("Stopping audio recording.")
            recognizer.stop_transcription()

if __name__ == "__main__":
    recognizer = RealTimeSpeechRecognizer(URL, TOKEN, APPKEY)
    start_audio_stream(recognizer)

这段代码实现了一个实时语音转文字系统,使用阿里云的语音转文字服务 (NlsSpeechTranscriber) 来处理从麦克风捕获的音频数据。以下是代码的详细解释:

主要模块和库

  • timethreading:用于处理时间和多线程。
  • queue:用于实现线程间通信的队列。
  • sounddevice (sd):用于从麦克风捕获音频数据。
  • numpy (np):用于处理音频数据数组。
  • nls:阿里云的语音服务库。
  • sys:用于处理系统相关的操作,如错误输出。

阿里云配置信息

URL = "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
TOKEN = "016ca1620aff421da8fac81b9fb52dc5"
APPKEY = "ahS8ZDaimkpWALHi"

这些变量存储了阿里云语音服务的配置信息,包括服务的 URL、令牌(TOKEN)和应用密钥(APPKEY)。

音频数据队列

audio_queue = queue.Queue()

用于存储从麦克风捕获的音频数据。

音频数据回调函数

def audio_callback(indata, frames, time, status):
    if status:
        print(status, file=sys.stderr)
    audio_queue.put(indata.copy())

这个回调函数会在音频数据可用时被调用,将捕获到的音频数据复制到队列 audio_queue 中。

RealTimeSpeechRecognizer 类

class RealTimeSpeechRecognizer:
    def __init__(self, url, token, appkey):
        self.url = url
        self.token = token
        self.appkey = appkey
        self.transcriber = None
        self.__initialize_transcriber()

初始化函数,接收 URL、TOKEN 和 APPKEY,并调用内部函数 __initialize_transcriber 初始化语音转文字服务。

def __initialize_transcriber(self):
    self.transcriber = nls.NlsSpeechTranscriber(
        url=self.url,
        token=self.token,
        appkey=self.appkey,
        on_sentence_begin=self.on_sentence_begin,
        on_sentence_end=self.on_sentence_end,
        on_start=self.on_start,
        on_result_changed=self.on_result_changed,
        on_completed=self.on_completed,
        on_error=self.on_error,
        on_close=self.on_close,
        callback_args=[self]
    )
    self.transcriber.start(aformat="pcm", enable_intermediate_result=True,
                           enable_punctuation_prediction=True, enable_inverse_text_normalization=True)

初始化语音转文字服务并配置相关回调函数。

def send_audio(self, audio_data):
    if self.transcriber:
        self.transcriber.send_audio(audio_data)

def stop_transcription(self):
    if self.transcriber:
        self.transcriber.stop()

用于发送音频数据到阿里云并停止转录。

回调函数

def on_sentence_begin(self, message, *args):
    print("Sentence begin: {}".format(message))

def on_sentence_end(self, message, *args):
    print("Sentence end: {}".format(message))

def on_start(self, message, *args):
    print("Start: {}".format(message))

def on_result_changed(self, message, *args):
    print("Result changed: {}".format(message))

def on_completed(self, message, *args):
    print("Completed: {}".format(message))

def on_error(self, message, *args):
    print("Error: {}".format(message))

def on_close(self, *args):
    print("Closed: {}".format(args))

这些函数在语音转文字服务的不同事件发生时被调用,打印相关信息。

处理音频数据

def recognize_speech(audio_data, recognizer):
    audio_data = np.concatenate(audio_data)
    recognizer.send_audio(audio_data.tobytes())

将音频数据连接成一个数组并发送给阿里云语音转文字服务。

开始音频流并处理音频数据

def start_audio_stream(recognizer):
    with sd.InputStream(callback=audio_callback, channels=1, samplerate=16000, dtype='int16'):
        print("Recording audio... Press Ctrl+C to stop.")
        audio_buffer = []
        try:
            while True:
                while not audio_queue.empty():
                    audio_buffer.append(audio_queue.get())
                if len(audio_buffer) >= 10:  # 调整音频数据块大小
                    audio_data = np.concatenate(audio_buffer)
                    recognize_speech(audio_data, recognizer)
                    audio_buffer = []  # Clear buffer after sending
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("Stopping audio recording.")
            recognizer.stop_transcription()

这个函数打开音频输入流,开始录音并处理音频数据,将其发送到阿里云进行转录。当用户按下 Ctrl+C 时,停止录音并结束转录。

主程序入口

if __name__ == "__main__":
    recognizer = RealTimeSpeechRecognizer(URL, TOKEN, APPKEY)
    start_audio_stream(recognizer)

创建一个 RealTimeSpeechRecognizer 实例并开始录音和处理音频数据。

通过这些步骤,代码实现了从麦克风捕获音频数据并实时发送到阿里云进行语音转文字的功能。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 首先,你需要申请百度的开发者账号,并获取你的应用的 API Key 和 Secret Key。 然后,你需要安装百度的 API 库,在命令行中使用 `pip install baidu-aip` 命令安装。 接下来,你可以使用以下代码调用百度 API 进行语音文字: ```python from aip import AipSpeech # 定义常量 APP_ID = 'your_app_id' API_KEY = 'your_api_key' SECRET_KEY = 'your_secret_key' # 初始化AipSpeech对象 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 读取音频文件 def get_file_content(file_path): with open(file_path, 'rb') as fp: return fp.read() # 调用百度的语音识别API def recognize(file_path): audio_data = get_file_content(file_path) result = client.asr(audio_data, 'pcm', 16000, { 'dev_pid': 1536, }) print(result) # 调用 recognize 函数 recognize('your_audio_file.pcm') ``` 上面的代码会将音频文件 `your_audio_file.pcm` 中的语音换为文字,并输出到控制台。 注意: 百度的语音识别 API 支持的音频格式有限,建议使用 PCM 格式的音频文件。 ### 回答2: Python 能够通过 HTTP 请求来调用百度 API 实现实时语音文字。首先,需要安装 Python 的 `requests` 库来发送 HTTP 请求。同时,还需要在百度开发者平台创建一个应用并获取 API Key 和 Secret Key。下面是一个用 Python 编写的示例程序: ```python import requests # 设置百度 API 相关信息 API_KEY = "YOUR_API_KEY" SECRET_KEY = "YOUR_SECRET_KEY" # 获取token def get_token(): url = "https://aip.baidubce.com/oauth/2.0/token" params = { "grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY } response = requests.post(url, params=params) token = response.json().get("access_token") return token # 识别语音 def speech_to_text(audio): token = get_token() url = "http://vop.baidu.com/server_api" # 将语音文件作为二进制数据进行传输 data = { "format": "wav", "rate": 16000, "channel": 1, "token": token, "cuid": "YOUR_CUID", "len": len(audio), "speech": audio } headers = { "Content-Type": "application/json" } response = requests.post(url, json=data, headers=headers) result = response.json().get("result") return result # 读取语音文件 def read_audio(file_path): with open(file_path, "rb") as audio_file: audio = audio_file.read() return audio # 将语音文件文字 def convert_audio_to_text(file_path): audio = read_audio(file_path) text = speech_to_text(audio) return text # 主程序 if __name__ == "__main__": file_path = "your_audio.wav" result = convert_audio_to_text(file_path) print(result) ``` 注意:上述程序中的 `YOUR_API_KEY`、`YOUR_SECRET_KEY` 和 `YOUR_CUID` 需要替换为你在百度开发者平台创建应用后获取到的相关信息。`your_audio.wav` 是待换的语音文件的路径。 以上代码是一个简单的百度实时语音文字的示例程序,可以根据需要进行扩展和优化,比如加入实时录音、错误处理等功能。 ### 回答3: 编写一个调用百度API的实时语音文字程序涉及以下步骤: 1. 导入必要的库和模块: ```python import requests from pyaudio import PyAudio, paInt16 import wave import base64 ``` 2. 设置百度API信息: 你需要去百度开放平台申请语音识别API的应用,并获取相应的API Key和Secret Key。 3. 设置录音参数并初始化PyAudio对象: ```python RATE = 16000 CHANNELS = 1 FORMAT = paInt16 CHUNK = 1024 audio = PyAudio() ``` 4. 创建录音函数以及将录音数据为base64编码的函数: ```python def record(): stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] while True: data = stream.read(CHUNK) frames.append(data) # 这里实现你的停止录音条件,例如按下某个键 stream.stop_stream() stream.close() audio.terminate() return frames def get_base64_data(frames): frame_data = b''.join(frames) base64_data = base64.b64encode(frame_data) return base64_data ``` 5. 创建函数用于调用百度API进行语音识别: ```python def get_speech_to_text(base64_data): url = 'https://openapi.baidu.com/oauth/2.0/token' headers = {'Content-Type': 'application/json; charset=UTF-8'} data = { 'grant_type': 'client_credentials', 'client_id': 'YOUR_API_KEY', 'client_secret': 'YOUR_SECRET_KEY' } response = requests.post(url, headers=headers, data=data) access_token = response.json()['access_token'] url = 'http://vop.baidu.com/server_api' headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Connection': 'keep-alive' } data = { 'format': 'wav', 'rate': RATE, 'channel': CHANNELS, 'token': access_token, 'cuid': 'YOUR_CUID', 'speech': base64_data } response = requests.post(url, headers=headers, json=data) result = response.json()['result'] return result ``` 6. 编写主程序来调用以上函数: ```python frames = record() base64_data = get_base64_data(frames) result = get_speech_to_text(base64_data) print(result) ``` 以上是用Python编写调用百度API的实时语音文字程序的基本步骤。根据需要可以添加适当的异常处理和界面或命令行的交互。注意在具体实现时,请根据百度API文档进行相应的参数设置和错误处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MonkeyKing.sun

对你有帮助的话,可以打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值