How to handle files using Cordova?

淺唱寂寞╮ 提交于 2019-12-02 02:45:45

The following code works for me.
Tested in MobileFirst Platform Foundation 7.1:

index.html

<button id="downloadMP3">Download MP3 file</button><br/>
<button id="playMP3" disabled>Play MP3 file</button>

main.js

var mediaFile;

function wlCommonInit(){
    $("#downloadMP3").click(downloadMP3);
    $("#playMP3").click(playMP3);
}

function downloadMP3() {
    var fileTransfer = new FileTransfer();
    var remoteFilePath = encodeURI("http://www.noiseaddicts.com/samples_1w72b820/4638.mp3");
    var localDownloadPath = cordova.file.dataDirectory + '4638.mp3';

    alert ("Downloading...");
    fileTransfer.download(
        remoteFilePath,
        localDownloadPath,
        function(successResponse) {
            mediaFile = successResponse.toURL();
            mediaFile = mediaFile.replace('file://','');
            $('#playMP3').prop('disabled', false);
        },
        function(errorResponse) {
            alert (JSON.stringify(errorResponse));
        }
    );
}

function playMP3() {
    var media = new Media(
        mediaFile,
        function() {
            alert("Playing audio file.");
        },
        function() {
            alert("Failed playing audio file.");
        }
    );

    media.play();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!