Python - 读取音频数据而不保存到文件
Python - Read Audio Data Without Saving to File
我正在浏览器和我的 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 数组并将编码后的音频数据发送回浏览器?
基于source code函数write
可以使用文件对象而不是文件名所以你可以尝试使用io.BytesIO()
在内存中创建file-like对象
我没法测试,但应该是这样的
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())
编辑:
我使用了 example from source code 并使用了 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)
我正在浏览器和我的 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 数组并将编码后的音频数据发送回浏览器?
基于source code函数write
可以使用文件对象而不是文件名所以你可以尝试使用io.BytesIO()
在内存中创建file-like对象
我没法测试,但应该是这样的
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())
编辑:
我使用了 example from source code 并使用了 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)