Search code examples
pythonamazon-web-serviceswavboto3amazon-lex

Python3 boto3 response to wav


I'm using AWS Lex to generate a response to my sound (http://boto3.readthedocs.io/en/latest/reference/services/lex-runtime.html).

The response audioStream is a StreamingBody object from boto3 (https://botocore.readthedocs.io/en/latest/reference/response.html#botocore.response.StreamingBody).

The question is how can I turn the returned byte array to a wav file that I can play with sox?

I have tried the following:

audio_stream = response['audioStream'].read()
f = open('response.wav', 'wb')
f.write(audio_stream)
f.close()

But then I get an error with sox and aplay that the format is invalid (RIFF header was not found)

I also tried to use the wave library with the following code

audio_stream = response['audioStream'].read()
f = wave.open('response.wav', 'wb')
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(16000)
f.writeframesraw(audio_stream)
f.close()

But then I only get white noise when I play the file and the length is very short.


Solution

  • The answer was to close the stream before writing it to the file. The working code looks like this:

        audio_stream = response['audioStream'].read()
        response['audioStream'].close()
    
        f = wave.open(self.response_fname, 'wb')
        f.setnchannels(2)
        f.setsampwidth(2)
        f.setframerate(16000)
        f.setnframes(0)
    
        f.writeframesraw(audio_stream)
        f.close()