Search code examples
cordovaionic-frameworkcordova-plugins

Ionic Cordova Media Not Found


I'm writing an Ionic app, and I'm trying to play an mp3 file using the Cordova Media (org.apache.cordova.media). But when I use the Media object in JavaScript I get: ReferenceError: Media is not defined

I've used both plain JS and ngCordova and the result is the same.

Plain JS:

var media = new Media('js/components/timer/startBell.mp3');
media.play();

ngCordova flavor:

var startBell source = ('js/components/timer/startBell.mp3');
var mediaSource = $cordovaMedia.newMedia(startBellSrc);
                    var promise = mediaSource.promise;
                    var mediaStatus = mediaSource.mediaStatus;
                    var media = mediaSource.media;
                    $cordovaMedia.play(media);

I'm new to both Cordova and to Ionic, so I'm not sure if I need to add something to the run in the app.js:

angular.module('myApp', [
    'ionic',
    'my.custom.module'
])

.run(function ($ionicPlatform, $cordovaMedia) {
    $ionicPlatform.ready(function () {
        **//add some cordova media plugin initialization code here???**
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

full stack trace:

ReferenceError: Media is not defined
    at Object.newMedia (http://localhost:8100/lib/ngCordova/dist/ng-cordova.js:1817:25)
    at Object.countdown (http://localhost:8100/js/components/timer/timer-service.js:14:53)
    at Scope.$scope.startTimer (http://localhost:8100/js/main/main-controller.js:6:30)
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:18227:21
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:42490:9
    at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20089:28)
    at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:20187:23)
    at HTMLButtonElement.<anonymous> (http://localhost:8100/lib/ionic/js/ionic.bundle.js:42489:13)
    at http://localhost:8100/lib/ionic/js/ionic.bundle.js:10381:10
    at Array.forEach (native) 

Solution

  • You are using the ionic serve method to preview your app, which isn't able to run Cordova (since its just a browser, not actually a mobile environment). You'll have to try testing by running your app inside of an emulator.