Python语音识别工具不能识别wav

2024-06-25 23:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经生成了一个.wav音频文件,其中包含一些在背景中有其他干扰语音的语音。 这段代码适用于test.wav文件:

    import speech_recognition as sr

    r = sr.Recognizer()
    with sr.WavFile(wav_path) as source:
        audio = r.record(source)

    text = r.recognize_google(audio)

如果我使用.wav文件,会出现以下错误:

ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format

如果我用soundfile保存这个.wav文件,情况会稍微好转:

^{pr2}$

然后将新保存的路径加载回第一个代码块,这次我得到:

if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()

音频文件保存为

    wavfile.write(wav_path, fs, data)

其中wav_path='数据.wav'. 有什么想法吗?在

解决方案:

按以下方式保存音频数据将生成正确的.wav文件:

    import wavio
    wavio.write(wav_path, data, fs ,sampwidth=2)

Tags: or文件path代码importsourceasnot
1条回答
网友
1楼 · 发布于 2024-06-25 23:50:30

speech_recognition包中的代码来看,它似乎使用来自Python标准库的wave来读取WAV文件。Python的wave库不处理浮点WAV文件,因此必须确保对以整数格式保存的文件使用speech_recognition。在

如果向SciPy传递一个整数数组,SciPy的函数scipy.io.wavfile.write将创建一个整数文件。因此,如果data是一个浮点numpy数组,可以尝试以下操作:

from scipy.io import wavfile

# Convert `data` to 32 bit integers:
y = (np.iinfo(np.int32).max * (data/np.abs(data).max())).astype(np.int32)

wavfile.write(wav_path, fs, y)

然后尝试使用speech_recognition读取该文件。在

或者,您可以使用^{}(我创建的一个小库)将数据保存到WAV文件中。它还使用Python的wave库来创建输出,因此speech_recognition应该能够读取它创建的文件。在

相关问题 更多 >