我有 3 个按钮来录制、停止和播放音频。 使用 MediaRecorder 可以轻松运行音频 blob。 当我尝试将 blob 作为文件上传到服务器时出现问题。 我有一个类型为文件的音频元素,一个录音标志(0或1),并且需要在停止录音时上传blob。
这是我的代码:
var thisAudioBlob = document.getElementById("audioElement");
var playFlag = 0;
function initFunction() {
async function getUserMedia(constraints) {
if (window.navigator.mediaDevices) {
return window.navigator.mediaDevices.getUserMedia(constraints);
}
let legacyApi =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (legacyApi) {
return new Promise(function (resolve, reject) {
legacyApi.bind(window.navigator)(constraints, resolve, reject);
return reject('rejected');
});
} else {
// === an alert
}
}
let audioChunks = [];
let rec;
let blob;
function handlerFunction(stream) {
rec = new MediaRecorder(stream);
rec.start();
rec.ondataavailable = (e) => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
blob = new Blob(audioChunks, { type: "audio/mp3" });
blobUrl = URL.createObjectURL(blob);
document.getElementById("audioElement").src = URL.createObjectURL(blob);
var recordedAudioPath = document.getElementById("audioElement").src;
tempAudioFilePathField.value = recordedAudioPath;
recordedAudioFlag = 1;
}
};
}
function startusingBrowserMicrophone(boolean) {
getUserMedia({ audio: boolean }).then((stream) => {
handlerFunction(stream);
});
}
startusingBrowserMicrophone(true);
myStopButton.addEventListener("click", (e) => {
if (playFlag != 1) {
try {
new File([thisAudioBlob], "audio_temp.mp3", {
type: thisAudioBlob.type,
lastModified:new Date().getTime()
});
} catch(error) {
// === manage error
}
rec.stop();
audioNoteFlagField.value = "1";
} else {
playFlag = 0;
thisAudioBlob.pause();
bulletIconDiv.style.color = "white";
myPlayButton.style.color = "white";
document.getElementById("audioElement").currentTime = 0.01;
audioText.textContent = "play per ascoltare...";
try {
new File([thisAudioBlob], "audio_temp.mp3", {
type: thisAudioBlob.type,
lastModified:new Date().getTime()
});
audioSaveAjax();
} catch(error) {
// === manage error
}
}
});
}
function audioSaveAjax() {
var fd = new FormData();
fd.append('fname', 'test_audio_file.mp3');
fd.append('data', thisAudioBlob);
$.ajax({
type: 'POST',
url: ‘get_audio.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// === say something through console
});
}
但没有获得音频文件。我只得到一个 25 个无意义字节的文件,没有其他任何东西。 我究竟做错了什么? 有什么帮助吗?
您要将
HTMLAudioElement
附加到 FormData
对象,您应该附加从音频块创建的 blob。
function audioSaveAjax() {
var fd = new FormData();
fd.append('fname', 'test_audio_file.mp3');
fd.append('data', blob, 'mp3 is free.mp3');
$.ajax({
type: 'POST',
url: 'get_audio.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// === say something through console
});
}