Javascript 将Wav文件从js发送到flask
我在js中有这个代码,它记录了来自浏览器的音频,我需要将它从js发送回flaskJavascript 将Wav文件从js发送到flask,javascript,jquery,flask,audio,backend,Javascript,Jquery,Flask,Audio,Backend,我在js中有这个代码,它记录了来自浏览器的音频,我需要将它从js发送回flask start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(options).then(function (stream) { myRecorder.objects.stream = stream; myRecorder.objects.reco
start: function () {
var options = {audio: true, video: false};
navigator.mediaDevices.getUserMedia(options).then(function (stream) {
myRecorder.objects.stream = stream;
myRecorder.objects.recorder = new Recorder(
myRecorder.objects.context.createMediaStreamSource(stream),
{numChannels: 1}
);
myRecorder.objects.recorder.record();
}).catch(function (err) {});
在以wav格式制作文件时,我应该如何做到这一点?以下示例创建有限时间的音频录制,并在完成后上载。包含blob的表单用于此操作。
也可以将纯blob传输到服务器,但由于所使用的音频格式因浏览器而异,因此这是更通用的变体
(function() {
const uploadURL = "{{ url_for('upload') }}";
const startButton = document.getElementById("toggle-rec-btn");
startButton.addEventListener("click", function() {
if (!navigator.mediaDevices) {
console.error("getUserMedia not supported.")
return;
}
const constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
let chunks = []
let recorder = new MediaRecorder(stream);
recorder.ondataavailable = event => {
// Collect all the chunks of the recording in an array.
chunks.push(event.data);
};
recorder.onstop = event => {
console.log("Recording stopped.")
// Create a blob with all the chunks of the recording.
let blob = new Blob(chunks, { type: recorder.mimeType });
chunks = [];
startButton.disabled = false;
// Create form data that contain the recording.
let formData = new FormData();
formData.append("audio_file", blob);
// Send the form data to the server.
fetch(uploadURL, {
method: "POST",
cache: "no-cache",
body: formData
}).then(resp => {
if (resp.status === 200) {
window.location.reload(true);
} else {
console.error("Error:", resp)
}
}).catch(err => {
console.error(err);
});
};
recorder.onstart = event => {
console.log("Recording started.");
startButton.disabled = true;
// Stop recording when the time is up.
setTimeout(function() { recorder.stop(); }, 10000);
};
recorder.start();
})
.catch(function(err) {
console.error(err);
});
});
})();
所有录制都保存在服务器上的默认名称为“var/app instance/uploads”的目录中
我祝愿你在实施你的项目时一切顺利
import os
from flask import abort, current_app, make_response, request
from mimetypes import guess_extension
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['POST'])
def upload():
if 'audio_file' in request.files:
file = request.files['audio_file']
# Get the file suffix based on the mime type.
extname = guess_extension(file.mimetype)
if not extname:
abort(400)
# Test here for allowed file extensions.
# Generate a unique file name with the help of consecutive numbering.
i = 1
while True:
dst = os.path.join(
current_app.instance_path,
current_app.config.get('UPLOAD_FOLDER', 'uploads'),
secure_filename(f'audio_record_{i}{extname}'))
if not os.path.exists(dst): break
i += 1
# Save the file to disk.
file.save(dst)
return make_response('', 200)
abort(400)