为Google语音API创建适当的WAV文件

9
我将使用pyaudio来录制我的声音并保存为wav文件。以下是我的代码:
```python ```
def voice_recorder():
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 22050
    CHUNK = 1024
    RECORD_SECONDS = 4
    WAVE_OUTPUT_FILENAME = "first.wav"

    audio = pyaudio.PyAudio()

    # start Recording
    stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)
    print "konusun..."
    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    #print "finished recording"


    # stop Recording
    stream.stop_stream()
    stream.close()
    audio.terminate()

    waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    waveFile.setnchannels(CHANNELS)
    waveFile.setsampwidth(audio.get_sample_size(FORMAT))
    waveFile.setframerate(RATE)
    waveFile.writeframes(b''.join(frames))
    waveFile.close()

我正在使用以下代码调用Google语音API,它可以将WAV文件中的语音转换为文本:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/api-client/transcribe.py 当我尝试将由pyaudio生成的WAV文件导入到Google的代码中时,我遇到了以下错误:
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://speech.googleapis.com/v1beta1/speech:syncrecognize?alt=json returned "Invalid Configuration, Does not match Wav File Header.
Wav Header Contents:
Encoding: LINEAR16
Channels: 2
Sample Rate: 22050.
Request Contents:
Encoding: linear16
Channels: 1
Sample Rate: 22050.">

我使用以下方法来解决这个问题:我用FFmpeg将WAV文件转换为MP3,然后再用Sox将MP3文件转换回WAV。
def wav_to_mp3():
    FNULL = open(os.devnull, 'w')
    subprocess.call(['ffmpeg', '-i', 'first.wav', '-ac', '1', '-ab', '6400', '-ar', '16000', 'second.mp3', '-y'], stdout=FNULL, stderr=subprocess.STDOUT)

def mp3_to_wav():
    subprocess.call(['sox', 'second.mp3', '-r', '16000', 'son.wav'])

谷歌的API可以使用这种WAV输出,但由于质量下降太多,它的性能不佳。

那么我该如何在第一步使用pyaudio创建与谷歌兼容的WAV文件呢?

1个回答

5
使用avconv将wav文件转换为flac文件并将其发送到Google语音API解决了问题。
subprocess.call(['avconv', '-i', 'first.wav', '-y', '-ar', '48000', '-ac', '1', 'last.flac'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接