使用PhoneGap将音频文件上传到iOS上的服务器

时间:2015-08-05 08:02:24

标签: ios cordova audio

我正在尝试录制音频,保存并将文件上传到服务器。

我有记录并将记录保存到Documents文件夹的代码。

function recordAudio() {
    window.src = "myrecording.wav";
    window.mediaRec = new Media(src, onSuccess, onError);

    mediaRec.stop();
    mediaRec.startRecord();

    var recTime = 0;
    setAudioPosition(recTime + " sec");
    var recInterval = setInterval(function() {
    recTime = recTime + 1;
    setAudioPosition(recTime + " sec");
    }, 1000);
    }
    function stopRecording() {
    mediaRec.stopRecord();
    mediaRec.play();

}
function onSuccess() {
    console.log("recordAudio():Audio Success");
}
function onError(error) {
    alert('code: '    + error.code    + '\n' + 
    'message: ' + error.message + '\n');
}
function setAudioPosition(position) {
    document.getElementById('audio_position').innerHTML = position;
}

我有两个问题:

  1. 如何访问录制的文件?它在哪里?我试过了documents://myrecording.wav。是不是?

  2. 如何将文件上传到我的服务器?

1 个答案:

答案 0 :(得分:0)

尝试使用media capture plugin而不是使用媒体插件

var captureSuccess = function(mediaFiles) {
    var i, path, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        path = mediaFiles[i].fullPath;
        uploadAudio(path);     
    }
};


var captureError = function(error) {
    navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};

navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:1});

如果您想使用媒体插件,则必须提供完整的文件网址,而不仅仅是名称,然后使用该网址使用file transfer plugin上传文件

使用file transfer plugin

function uploadAudio(fileURL) {
    var win = function (r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
    }

    var fail = function (error) {
        alert("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
    }

    var options = new FileUploadOptions();
    options.fileKey = "file";//the name of the file you expect on the server
    options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);

    var ft = new FileTransfer();
    ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);

}