I am using the ionic framework to create an app. I would like to play a sound so I used https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/ . This is my piece of code used to play the sound:
var my_media = new Media('/android/assets/www/audio/National Anthem.mp3',
// success callback
function () { console.log("playAudio():Audio Success"); },
// error callback
function (err) {console.dir("playAudio():Audio Error: " + err); }
);
my_media.play();
Unfortunately its not playing and the error message given is:
playAudio():Audio Error: [object Object]
In which I cannot view the object on the chrome console!
If I replace var my_media = new Media(..
with var my_media =$cordovaMedia.newMedia(...
I dont get any message at all on the console. My code is placed in $ionicPlatform.ready(function()..
so I know for sure that the plugin is ready before using it. Any sugesstions?
So my solution for media player is below:
First, create a service:
.factory('MediaSrv', function($q, $ionicPlatform, $window){
var service = {
loadMedia: loadMedia,
getStatusMessage: getStatusMessage,
getErrorMessage: getErrorMessage
};
function loadMedia(src, onError, onStatus, onStop){
var defer = $q.defer();
$ionicPlatform.ready(function(){
var mediaSuccess = function(){
if(onStop){onStop();}
};
var mediaError = function(err){
_logError(src, err);
if(onError){onError(err);}
};
var mediaStatus = function(status){
if(onStatus){onStatus(status);}
};
if($ionicPlatform.is('android')){src = '/android_asset/www/' + src;}
defer.resolve(new $window.Media(src, mediaSuccess, mediaError, mediaStatus));
});
return defer.promise;
}
function _logError(src, err){
console.error('media error', {
code: err.code,
message: getErrorMessage(err.code)
});
}
function getStatusMessage(status){
if(status === 0){return 'Media.MEDIA_NONE';}
else if(status === 1){return 'Media.MEDIA_STARTING';}
else if(status === 2){return 'Media.MEDIA_RUNNING';}
else if(status === 3){return 'Media.MEDIA_PAUSED';}
else if(status === 4){return 'Media.MEDIA_STOPPED';}
else {return 'Unknown status <'+status+'>';}
}
function getErrorMessage(code){
if(code === 1){return 'MediaError.MEDIA_ERR_ABORTED';}
else if(code === 2){return 'MediaError.MEDIA_ERR_NETWORK';}
else if(code === 3){return 'MediaError.MEDIA_ERR_DECODE';}
else if(code === 4){return 'MediaError.MEDIA_ERR_NONE_SUPPORTED';}
else {return 'Unknown code <'+code+'>';}
}
return service;
})
Then, in controller:
.controller('phrasebookCtrl', function ($scope, $ionicPlatform, $timeout, $cordovaMedia,MediaSrv) {
$scope.play = function(src){
MediaSrv.loadMedia(src).then(function(media){
media.play();
});
And in your view (on click Test me):
<p>Welcome: <a ng-click="play('audio/welcome1_el.mp3')">Test me</a></p>
Note: This solution works fine for Android and iOS platforms. Also you must create a folder with the name audio in www folder in your project, with the .mp3 files.
Please let me know if this solved your problem.