简体   繁体   中英

Upload audio file to server on iOS using PhoneGap

I'm trying to record audio, save it and upload the file to server.

I have the code that records and saves the recording to Documents folder.

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;
}

I have 2 questions:

  1. How to access the recorded file? Where is it located? I've tried documents://myrecording.wav . Is it right?

  2. How to upload the file to my server?

Try with media capture plugin instead of using media 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});

If you want to use media plugin, you have to provide a full file url, not just the name, and then use that url to upload the file using file transfer plugin

To use 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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM