我在浏览器和AWS Lambda函数之间发送音频数据,但我发现自己正在为功能目的保存文件的中间步骤。下面是我现在要工作的代码:
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
}
但是,是否有更明智的方法来转换我的numpy数组并将编码的音频数据发送回浏览器?
发布于 2020-09-25 08:28:31
基于源代码函数,write
可以使用文件对象而不是文件名,因此您可以尝试使用io.BytesIO()
在内存中创建类似文件的对象。
我不能测试,但应该是这样的
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())
编辑:
我用了来自源代码的示例,用了io.BytesIO()
,它很管用
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)
https://stackoverflow.com/questions/64059411
复制相似问题