在lambda函数中将mp3文件作为HTTP响应返回

2024-09-28 05:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python3.6Lambda函数,运行在AWS上,由API网关调用,它使用ffmpeg连接一些mp3文件。我希望生成的mp3文件作为lambda响应返回

我创建的组合mp3如下所示:

p = subprocess.Popen(conversion_command, stdin=stdin_parameter, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p_out, p_err = p.communicate()
p_out = bytearray(p_out)

使用这些参数:

conversion_command = ['ffmpeg',
                          '-y',  # always overwrite existing files
                          '-i', 'concat:one.mp3|two.mp3|three.mp3',
                          ]

stdin_parameter = subprocess.PIPE
conversion_command += [
        "-vn",  # Drop any video streams if there are any
        "-f", "mp3",  # output options (filename last)
        "-"
    ]

该数组如下所示:

bytearray(b'ID3\x04\x00\x00\x00\x00\x00#TSSE\x00\x00\x00\x0f\x00\x00\x03Lavf58.45.100\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xf38\xc4\x00\x11\xd1RH-L\x10\x00\x0cX\x05\xf6$\x03@ \x07\x04E\r\x92\x04\x82a\x81\xe2\xc7;h\xb1\xcaS\xa6fB5N\xf3\x9f\xa9\xdf\xff\xa19\xf3\x9d\xe4!\x1aB\x10\x84!\'\x00\x00"\xc1\xff\xff\xa8\x06\x0f\x9f\xff\xf2\x99\xaf\xfc\x1f~\x0f\x87\xe5\xdfX>\x08\x06\x15\xcb\xef\xf3\xfc\xff\xf5\xd7Mp<\xec1\xcd\xc0^\x94\xb3Q\t9d\xc7\x88\xff\xf38\xc4\x17\x1a\xb1\xb6\xb9\x95\x8f8\x00z.\xf2\xfa>\xe1(\x96`\xa8|\x8b\xb5\xd0\x1f\x88\x83d+\x1d\xf9c\xd8\xf4dM\xd5\xf9\xcb\x1e\x1d/\xee\xbd\x9b{\xa1\xaeMQ\xf56\xc66\xf8\xd0|\xb21\x17`\xc3\xf6w\xe9P\xb02Y\xcf\xf2\x8e\xdd\xe1\xb0p\x1f\x08\x89\x80!\xc0\x90@\xe0\x0c\xb8\xe8Q\xbf\xf0s\xfee\x02\xe9\x06R\xe9\xc5+\xccrGD\xff\xf38\xc4\x0b\x17\xf2~\xa4Q\xd8(\x00\x01\x88\x94Z\x13\xb2\xed?\xb2\xe7\xd4\xbb\xed\xf3O\xa4\x89\xc0\x0f\x1b\xe9 etc

如果执行以下操作,将成功重新创建mp3文件:

f = open('output.mp3', 'w+b')
binary_format = bytearray(p_out)
f.write(binary_format)
f.close()

我正在形成我的HTTP响应,如下所示:

responseObject = {}
responseObject['statusCode'] = 200
responseObject['headers'] = {}
responseObject['headers']['Content-Type'] = 'audio/mpeg'
responseObject['isBase64Encoded'] = 'true'

response = base64.b64encode(p_out)
response = response.decode('utf-8')
responseObject['body'] = response

return responseObject

这成功地使浏览器(chrome)显示媒体控件,但我没有听到任何音频。显然,这个音频没有正确地呈现给HTTP响应,但我不确定哪里出了问题

有人能帮忙吗


Tags: 文件responsestdinoutmp3commandsubprocesspipe
1条回答
网友
1楼 · 发布于 2024-09-28 05:24:30

好的,我已经开始工作了。一个简单的改变:

responseObject['isBase64Encoded'] = True

但主要问题是您需要在API网关中启用二进制支持。这篇帖子和@Kyler Laird的评论给了我需要的方向:

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html

通过将二进制媒体类型设置为/,我在api中启用了支持。我认为音频/mpeg就足够了

相关问题 更多 >

    热门问题