gpt4 book ai didi

python - Python-读取音频数据而不保存到文件

转载 作者:行者123 更新时间:2023-12-03 00:23:24 37 4
gpt4 key购买 nike

我正在浏览器和我的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()在内存中创建类似文件的对象
我无法测试,但应该是这样

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)

关于python - Python-读取音频数据而不保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64059411/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com