我正在尝试使用Flask将一个.wav音频文件(blob)从JS发送到Python。我只想将文件保存在Python端,并能够在我的计算机上播放它。这是我的尝试:
JS:
fetch(serverUrl, {
method: "post",
body: blob
});
其中blob的类型为Blob {size: 5040, type: "audio/wav;"}
Python:
@app.route('/messages', methods = ['POST'])
def api_message():
# Open file and write binary (blob) data
f = open('./file.wav', 'wb')
f.write(request.data)
f.close()
return "Binary message written!"
文件已保存但仅包含[object BlobEvent]
的shitload。我做错了什么,我该如何解决?
修改
使用MediaRecorder()
const mediaRecorder = new MediaRecorder(stream);
// Start
const chunks = [];
mediaRecorder.ondataavailable = e => {
chunks.push(e);
}
// On stop
blob = new Blob(chunks, {'type': 'audio/wav;'});
我尝试在客户端再次播放音频,但效果很好:
const audio = document.createElement('audio');
const audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
答案 0 :(得分:3)
您正在将一组事件对象传递给Blob构造函数而不是音频数据
数据为e.data
,因此您的代码应为
mediaRecorder.ondataavailable = e => {
chunks.push(e.data);
}
答案 1 :(得分:1)
您可以在 javascript
中上传分段文件export function uploadAudio(audioBlob) {
let data = new FormData();
data.append('file', audioBlob);
return axios
.post(`http://localhost:3030/audiorecog`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res)
return res
});
}
在 Python 中,您可以接收blob并将其保存
@app.route('/audiorecog', methods = ['GET', 'POST'])
def audiorecog():
if request.method == 'POST':
print("Recieved Audio File")
file = request.files['file']
print('File from the POST request is: {}'.format(file))
with open("audio.wav", "wb") as aud:
aud_stream = file.read()
aud.write(video_stream)
return "Success"
return 'Call from get'
答案 2 :(得分:0)
您是否尝试过使用FormData?
var form = new FormData();
form.append('file', BLOBDATA, FILENAME);
$.ajax({
type: 'POST',
url: 'ServerURL',
data: form, // Our pretty new form
cache: false,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
在python端,您可以通过执行以下操作来检查数据是否存在:
@app.route('/messages', methods=['POST'])
def api_message():
app.logger.debug(request.files['file'].filename)