使用speech_recognition库报错:audio_data需为合法音频数据的问题
解决soundcard录制音频无法传入speech_recognition识别的问题
问题根源
soundcard录制返回的data是numpy浮点数组,而speech_recognition的recognize_google方法仅接受该库封装的AudioData对象,或通过AudioFile/Microphone读取的音频源,直接传numpy数组会触发类型不匹配报错。
解决方案1:将numpy数组转换为AudioData对象
直接处理录制的数组,转换成speech_recognition要求的格式:
import numpy as np import soundcard as sc import speech_recognition as sr OUTPUT_FILE_NAME = "out.wav" # 文件名 SAMPLE_RATE = 48000 # 采样率[Hz] RECORD_SEC = 5 # 录制时长[秒] # 录制扬声器回环音频 with sc.get_microphone(id=str(sc.default_speaker().name), include_loopback=True).recorder(samplerate=SAMPLE_RATE) as mic: data = mic.record(numframes=SAMPLE_RATE * RECORD_SEC) # 适配speech_recognition的音频格式要求 # 1. 立体声转单声道(识别无需立体声,取声道平均值) if data.ndim > 1: data = np.mean(data, axis=1) # 2. 将float32格式(范围[-1,1])转为int16格式(PCM标准,范围[-32768,32767]) data_int16 = (data * 32767).astype(np.int16) # 3. 创建符合要求的AudioData对象 audio_data = sr.AudioData(data_int16.tobytes(), sample_rate=SAMPLE_RATE, sample_width=2) # 调用Google语音识别 r = sr.Recognizer() try: text = r.recognize_google(audio_data, language='en-US', show_all=False, key=None) print(text) except sr.UnknownValueError: print("Google语音识别无法理解音频内容") except sr.RequestError as e: print("无法从Google语音识别服务获取结果;{0}".format(e))
解决方案2:保存为WAV文件后读取识别
先把录制的音频存为标准WAV文件,再用speech_recognition加载识别:
import soundcard as sc import soundfile as sf import speech_recognition as sr OUTPUT_FILE_NAME = "out.wav" # 文件名 SAMPLE_RATE = 48000 # 采样率[Hz] RECORD_SEC = 5 # 录制时长[秒] # 录制并保存为WAV文件 with sc.get_microphone(id=str(sc.default_speaker().name), include_loopback=True).recorder(samplerate=SAMPLE_RATE) as mic: data = mic.record(numframes=SAMPLE_RATE * RECORD_SEC) sf.write(OUTPUT_FILE_NAME, data, SAMPLE_RATE) # 读取WAV文件并执行识别 r = sr.Recognizer() with sr.AudioFile(OUTPUT_FILE_NAME) as source: audio_data = r.record(source) try: text = r.recognize_google(audio_data, language='en-US', show_all=False, key=None) print(text) except sr.UnknownValueError: print("Google语音识别无法理解音频内容") except sr.RequestError as e: print("无法从Google语音识别服务获取结果;{0}".format(e))
内容的提问来源于stack exchange,提问作者ProfessionalAli
相关产品推荐
相关产品推荐

