Reputation: 1769
I am sending audio data between the browser and my AWS Lambda function, but I find myself doing an intermediate step of saving to file for functionality purposes. Here is my code right now to work:
wavio.write(file="out.wav", data=out_file, rate=16000, sampwidth=2) # where out_file is np.array
encode_output = base64.b64encode(open("out.wav", "rb").read())
return {
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
'Content-Type': 'audio/wav'
},
'statusCode': 200,
'body': encode_output,
'isBase64Encoded': True
}
However, is there a smarter way to convert my numpy array and send encoded audio data back to the browser?
Upvotes: 0
Views: 1505
Reputation: 142859
Base on source code function write
can use file object instead of filename so you can try to use io.BytesIO()
to create file-like object in memory
I couldn't test it but it should be something like this
import io
# ... code ...
file_in_memory = io.BytesIO()
wavio.write(file=file_in_memory, ...)
file_in_memory.seek(0) # move to the beginning of file
encode_output = base64.b64encode(file_in_memory.read())
EDIT:
I took example from source code and used io.BytesIO()
and it works
import numpy as np
import wavio
import base64
import io
rate = 22050 # samples per second
T = 3 # sample duration (seconds)
f = 440.0 # sound frequency (Hz)
t = np.linspace(0, T, T*rate, endpoint=False)
x = np.sin(2*np.pi * f * t)
file_in_memory = io.BytesIO()
wavio.write(file_in_memory, x, rate, sampwidth=3)
file_in_memory.seek(0)
encode_output = base64.b64encode(file_in_memory.read())
print(encode_output)
Upvotes: 1