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

Python-读取音频数据而不保存到文件,python,audio,aws-lambda,base64,Python,Audio,Aws Lambda,Base64,我正在浏览器和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&qu

我正在浏览器和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数组并将编码的音频数据发送回浏览器?

基于函数
写入
可以使用文件对象而不是文件名,因此您可以尝试使用
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)

您可以尝试使用
io.BytesIO()
在内存中创建类似文件的对象,但只有当函数
write
可以使用类似文件的对象而不是文件名时,它才会起作用。