如何使用Cordova处理文件?

时间:2015-10-25 05:42:57

标签: cordova ibm-mobilefirst

注意:此问题正在重新发布,因为无论出于何种原因,原始海报决定在提供并接受答案后将其删除。因此,我再次添加它以保存知识

原始问题:

我试图在Hybrid应用程序中使用apache cordova api来保存localhost:8080 / filename.mp3中的文件并将其下载到应用程序中并在android中打开本地文件.mp3。它无效。请帮助我。

以下是代码:

main.js

 function wlCommonInit(){
//playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");
}

         //!! Assumes filePath is a valid path on the device
      function DownloadAudio() {

    var fileTransfer = new FileTransfer();
       var uri = encodeURI("http://192.168.1.2:8080/tail_toddle.mp3");

    fileTransfer.download(
uri,
filePath,
function(entry) {
    console.log("download complete: " + entry.fullPath);
},
function(error) {
    console.log("download error source " + error.source);
    console.log("download error target " + error.target);
    console.log("upload error code" + error.code);
}
  );

     }

     // Audio player
  //
   var my_media = null;
   var mediaTimer = null;

    // Play audio
    //
     function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);

// Play audio
my_media.play();

// Update my_media position every second
if (mediaTimer == null) {
    mediaTimer = setInterval(function() {
        // get my_media position
        my_media.getCurrentPosition(
            // success callback
            function(position) {
                if (position > -1) {
                    setAudioPosition((position) + " sec");
                }
            },
            // error callback
            function(e) {
                console.log("Error getting pos=" + e);
                setAudioPosition("Error: " + e);
            }
        );
    }, 1000);
}
          }

      // Pause audio
          //
     function pauseAudio() {
           if (my_media) {
             my_media.pause();
         }
    }

 // Stop audio
 //
function stopAudio() {
if (my_media) {
    my_media.stop();
`enter code here`  }
   clearInterval(mediaTimer);
    mediaTimer = null;
  }

  // onSuccess Callback
  //
   function onSuccess() {
    console.log("playAudio():Audio Success");
        }

  // onError Callback
//
 function onError(error) {
   alert('code: '    + error.code    + '\n' +
        'message: ' + error.message + '\n');
 }

// Set audio position
       //
      function setAudioPosition(position) {
   document.getElementById('audio_position').innerHTML = position;
      }

的index.html

     <!DOCTYPE HTML>
   <html>
        <head>
        <meta charset="UTF-8">
        <title>index</title>
                 <meta name="viewport" content="width=device-width, initial-    scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
        <link rel="shortcut icon" href="images/favicon.png">
        <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
        <link rel="stylesheet" href="css/main.css">
        <script>window.$ = window.jQuery = WLJQ;</script>
    </head>
    <body style="display: none;">
        <!--application UI goes here-->
        Hello Worklight - Cordova Media API<br/><br/>

        <a href="#" class="btn large" onclick="DownloadAudio;">Download           Audio</a> - remote URL<br/>
        <a href="#" class="btn large" onclick="playAudio('/android_asset/www/default/audio/tail_toddle.mp3');">Play Audio</a> - local asset<br/>
        <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a><br/>
        <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a><br/>
        <p id="audio_position"></p>
        <script src="js/initOptions.js"></script>
        <script src="js/main.js"></script>
        <script src="js/messages.js"></script>
    </body>

我添加了一个新的删除功能:

的index.html:

<a href="#" class="btn large" onclick="deleteAudio();">Delete the local MP3 file</a><br/>

main.js:

function deleteAudio() {
  var entry= "file:///data/data/com.TestApp/files/4638.mp3";
  function success(entry) {
    alert("Removal succeeded");
 }

  function fail(error) {
    alert('Error removing file: ' + error.code);
 }

// remove the file
entry.remove(success, fail);
}

为什么要删除,它不会删除代码。我收到了这个错误:

10-11 09:54:14.419: E/NONE(1821): Uncaught Exception: Uncaught TypeError: Object file:///data/data/com.TestApp/files/4638.mp3 has no method 'remove' at (compiled_code):68

我可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

以下代码适用于我 在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();
}