我使用Matt Diamond的recorder.js瀏覽HTML5音頻API,並感覺這個問題可能有明顯的答案,但我找不到任何特定的文檔。RecorderJS通過AJAX上傳記錄的blob
問題:錄製一個wav文件後,如何通過ajax將該wav發送到服務器?有什麼建議麼???
我使用Matt Diamond的recorder.js瀏覽HTML5音頻API,並感覺這個問題可能有明顯的答案,但我找不到任何特定的文檔。RecorderJS通過AJAX上傳記錄的blob
問題:錄製一個wav文件後,如何通過ajax將該wav發送到服務器?有什麼建議麼???
如果你有blob,你需要把它變成一個url並通過ajax調用來運行url。
// might be nice to set up a boolean somewhere if you have a handler object
object = new Object();
object.sendToServer = true;
// You can create a callback and set it in the config object.
var config = {
callback : myCallback
}
// in the callback, send the blob to the server if you set the property to true
function myCallback(blob){
if(object.sendToServer){
// create an object url
// Matt actually uses this line when he creates Recorder.forceDownload()
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create a new request and send it via the objectUrl
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "blob";
request.onload = function(){
// send the blob somewhere else or handle it here
// use request.response
}
request.send();
}
}
// very important! run the following exportWAV method to trigger the callback
rec.exportWAV();
讓我知道如果這個工程..沒有測試過,但它應該工作。乾杯!
我也花了很多時間試圖實現你在這裏嘗試做的事情。我只能在實現FileReader並調用readAsDataURL()將blob轉換爲表示文件數據的data:URL(檢出MDN FileReader)後才能成功上傳音頻blob數據。您還必須POST,而不是GET FormData。這是我工作代碼的作用域代碼片段。請享用!
function uploadAudioFromBlob(assetID, blob)
{
var reader = new FileReader();
// this is triggered once the blob is read and readAsDataURL returns
reader.onload = function (event)
{
var formData = new FormData();
formData.append('assetID', assetID);
formData.append('audio', event.target.result);
$.ajax({
type: 'POST'
, url: 'MyMvcController/MyUploadAudioMethod'
, data: formData
, processData: false
, contentType: false
, dataType: 'json'
, cache: false
, success: function (json)
{
if (json.Success)
{
// do successful audio upload stuff
}
else
{
// handle audio upload failure reported
// back from server (I have a json.Error.Msg)
}
}
, error: function (jqXHR, textStatus, errorThrown)
{
alert('Error! '+ textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
// handle audio upload failure
}
});
}
reader.readAsDataURL(blob);
}
'FormData.append'也採用blob,因此您可以將音頻作爲文件發送。 'formData.append('audio',blob,'filename.ext');' – Musa 2014-01-11 00:53:16
@Musa當我向FormData附加一個blob時,它不會顯示在服務器上的FormCollection對象中(ASP.NET MVC3)。想知道是否有辦法直接將Blob傳遞給服務器,而不必先使用FileReader讀取它,但在我所有的研究中,我還沒有找到辦法做到這一點。 – 2014-01-16 16:43:34
它將顯示爲一個文件。你可以直接用'XMLHttpRequest.send'發送一個blob,但是我不知道你將如何在asp.net上讀取它。 – Musa 2014-01-16 16:47:19
謝謝,兄弟。我今晚會測試它! @cjroe – Todd 2013-02-22 20:38:21
@Todd爲你做了這項工作?我試圖做的一樣,請參閱http://stackoverflow.com/questions/15795678/upload-audio-recorded-in-browser-using-html5 – Adrian 2013-04-09 17:48:18
非常感謝。我忘了選擇那個答案是正確的,但是,已經很久了,我忘記了這是否需要調整。我很確定這個代碼的工作就像一個魅力! – Todd 2013-04-09 23:40:14