Create suitable WAV files for the Google Speech API

I use pyaudio to record my voice as a wav file. I am using the following code:

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() 

I use the following code for the Google Speech API, which basically converts speech into a WAV file into text: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/api-client/transcribe.py p >

When I try to import the wav file that pyaudio generates into Google code, I get the following error:

 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."> 

I use the following workaround for this: I convert a WAV file to MP3 using ffmpeg, after which I again convert an MP3 file to wav using sox:

 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']) 

The Google API works with this WAV output, but since the quality decreases too much, it does not work well.

So, how can I create a Google compatible WAV file using pyaudio in the first step?

+8
python wav pyaudio google-speech-api
source share
1 answer

Converting a wav file to a flac file using avconv and sending it to the Google Speech API solved the problem

 subprocess.call(['avconv', '-i', 'first.wav', '-y', '-ar', '48000', '-ac', '1', 'last.flac']) 
+4
source share

All Articles