cordova: media.getDuration returns -1

放肆的年华 提交于 2020-06-16 04:24:11

问题


I am using Media.getDuration() function to get duration of an audio file but I am always getting -1 as response.

This works fine if I build using build.phonegap.com

But whenever I build using cli I then getDuration does not work.

Following are simple steps to reproduce this issue:

CLI:

cordova start my_project
cordova plugin add cordova-plugin-media
cordova platform add android
cordova build android

www/index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
              "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Media Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);


    function deviceready()
    {
       var my_media = new Media('http://web.com/mp3');
       my_media.play();
       console.log(my_media.getDuration()); // this will produce -1
    }


    </script>
  </head>
  <body>

  </body>
</html>

回答1:


Alright I got solution. I was using using old version of media plugin by default ( i think 2.0 ) I used removed old plugin with following command:

cordova plugin remove cordova-plugin-media

Then I installed latest version of same plugin by using following command:

cordova plugin add cordova-plugin-media@2.2.0

And then I buit it again and it worked like charm.

Thanks




回答2:


var ruta="/android_asset/www/sounds/M.mp3"; 
$scope.audiofile = new Media(ruta);
$scope.audiofile.play();

var timerDur = setInterval(function () {
    $scope.dur = $scope.audiofile.getDuration();
    if ($scope.dur > 0) {
        clearInterval(timerDur);
        console.log($scope.dur + " sec");
    }    
}, 1);

cordova plugin remove cordova-plugin-media

Then I installed latest version of same plugin by using following command:

cordova plugin add cordova-plugin-media@2.3.0



回答3:


I always get -1 when trigger getDuration(). Here a solution reference, I found from ionic forum

getMediaDuration(path): Promise<any> {
    return new Promise((resolve, reject) => {
      let audio: MediaObject = this.media.create(path);
      audio.seekTo(1);
      audio.onStatusUpdate.subscribe(status => {
        setTimeout(()=>{
          resolve(audio.getDuration());
          audio.release();
        }, 500);

      }); 
    });
  }

Tag: ionic 4, cordova-plugin-media, getDuration(), media.getDuration



来源:https://stackoverflow.com/questions/35525276/cordova-media-getduration-returns-1

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