Playing Audio In Your Android And iOS Ionic Framework App

One of my Twitter followers recently asked me to do a post regarding audio and Ionic Framework.  Being the fiddler that I am, I decided to meet this request.

Using Ionic Framework, the Apache Cordova Media plugin, and ngCordova, we are going to make a very simple application with basic media controls.

Let’s start things off by creating a fresh Ionic project with Android and iOS support:

Remember, if you aren’t developing on a Mac, you cannot add and build for iOS.

Even though we will be using the AngularJS extension set, ngCordova, we still need to install the base Apache Cordova plugin.  Install the plugin by running the following from the root of your project:

With the plugin installed, lets go ahead and start setting up ngCordova.  Download and copy ng-cordova.min.js into your project’s www/js directory.  You’ll notice the version of ngCordova I referenced is not the latest, but instead from repository commit 9f907a65.  Since ngCordova is still alpha / beta, it is constantly changing and could introduce breaking changes.  This is the version I used when writing this tutorial.  Even though it is older, it still accomplishes the job no problem.  With the library file in place, open your index.html file and make it look similar to the following:

It is important to note that ng-cordova.min.js must come before cordova.js in your script includes.  Your project will not work correctly if it comes after.

One more thing must happen before we can start using the media plugin.  We must inject ngCordova into the AngularJS module dependencies.  Open your app.js file and make your angular.module look like the following:

At this point we can start using audio functionality in our application.

Let’s create a new controller like the following:

In the above controller you’ll notice a few things.  In the $scope.play function you’ll notice that I am not loading the media like ngCordova recommends.  I am instead loading the media like Apache Cordova recommends.  I decided to do it this way because it gives me very easy access to the status callback.  The ngCordova way returns a media status, but I found it would have been trickier to monitor.

In the status callback, you’ll notice that I show a loading notification if the status is Media.MEDIA_STARTING.  When the status is anything else like running or stopped, I hide the notification.  This is useful if you’re playing audio from the internet, where there could be long load times.  Below is a list of all the current media statuses:


Status Value
Media.MEDIA_NONE 0
Media.MEDIA_STARTING 1
Media.MEDIA_RUNNING 2
Media.MEDIA_PAUSED 3
Media.MEDIA_STOPPED 4

So how do we actually use the $scope.play function?  You can do something very simple like the following in your index.html file:

Please note that the MP3 in this example is just a random one I found publically on the internet.

So what happens if you don’t want to play audio from the internet?  Using our same $scope.play function, lets do the following in our index.html file:

The above snippet will try to play a song from the file system.  For example, if you’re on an Android device it will try to play /storage/emulated/0/www/mp3/song.mp3 where /storage/emulated/0 is your public storage accessible from any application.  On Android, if you’d like to play audio bundled with your application you would need to include /android_asset/ at the beginning of your path.  For example, /android_asset/www/mp3/song.mp3 would play a song found in your Ionic www/mp3 directory.

There are plenty of other cool things you can do with the media plugin.  You can find more on the subject via the official ngCordova or Apache Cordova Media documentation.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Tanish

    Thanks a ton for your blog. I was able to finally get the audioworking..

  • Martin

    Nic, excellent write up. One question. I’m deploying to iOS and audio stops playing when screen is locked. Any advice?

  • Oak Krittee

    how to add stop button for this example? please help me.

    • The documentation says to just use:


      $cordovaMedia.stop(source);

      In the example source = media. However, since media is not global to the controller in the example you’ll have to make it so. You need to do **var media = null** outside of the play method. If you don’t, source will just be undefined when you try to stop it.

      Regards,

  • Nima

    Hi, i did every thing , but i didn’t play, i use android 4.4.2 . i saw your movie several time , how to debug it?can i download your apk?

    • Hi Nima,

      Are you using a device or simulator?

      With the device connected, run ‘adb logcat’ and see what the error message is. If it doesn’t play, I’m sure it’s either buffering or there is an error.

      Let me know.

      Regards,

  • WebMedia TV

    Hi Nic, i used this example to create music app but when click on the music to play it, it goes to another page though used ui-router in my ionic project but i want it to stay in that page anytime i click on the music to play. thanks

    • It should not be taking you to another page. My assumption is you missed a step or have a typo.

      Can you look at the logs and see if there are any errors?

      Regards,

      • WebMedia TV

        Thanks for your quick response, this is controller,js

        angular.module(‘audio.controllers’,[])

        facebook.controller(“AudioController”, function($scope, $cordovaMedia, $ionicLoading, $location) {

        $scope.play = function(src, mediaSuccess, mediaError, mediaStatus) {

        var media = new Media(src, null, null, mediaStatusCallback);

        $cordovaMedia.play(media, { playAudioWhenScreenIsLocked : false });

        $location.path(“/new_release”);

        }

        var mediaStatusCallback = function(status) {

        if(status == 1) {

        $ionicLoading.show({template: ‘Loading…’});

        } else {

        $ionicLoading.hide();

        }

        }

        });

        html

        BECCA

        Move ft.Uhuru

        Start listening

        and i use $urlRouterProvider.otherwise(‘/home’); }); in my app.js for ui-router but if i click on the music to play it will take me to home page instead and also the music will keep playing. thanks

        • Hi,

          It is very difficult to read code in the comments section of a blog. If you want to share large piece of code, please do everyone a favor and use code tags or post on GitHub so the code retains format.

          Your app changes pages when you try to play the music because you have a $location.path("/new_release"); in your play method. It starts the track and immediately changes pages.

          Hopefully that helps.

          Regards,

  • WebMedia TV

    Hi Nic thanks for ur quick response and everything is working now thanks to u but i m developing music app with ionic and i will like all the music to play from server but i dont know to do that pls help me out on it. thanks and God bless u

    • Hi,

      Creating a music manager is out of my scope of knowledge. I suggest you do some Google searches or reach out on the Ionic Framework forums.

      Sorry,

      • WebMedia TV

        thanks, i finally got soundmanager2 working on mobile devices

        • Sat Mandir Khalsa

          Hi,

          I’m also interested in implementing soundmanager2 in ionic. Can you tell me what you needed to do to get it working? Do you have it working on both iOS and Android?

  • Bryan Villafañe

    What’s the path for iOS when the audio is in www/mp3/sound.mp3 ? In Android is /android_asset/www/mp3/sound.mp3

    • According to the Apache Cordova documentation for File, you can make use of the following:

      cordova.file.applicationDirectory

      I believe the iOS path is too complicated without it. With that said, you should be able to access your audio file like this:

      var filePath = cordova.file.applicationDirectory + “www/mp3/sound.mp3”;

      Don’t forget to install the Apache Cordova File plugin though. Hopefully this helps.

      Regards,

      • Bryan Villafañe

        I just tried it but it doesn’t work on iOS, I changed it for Android and it works.
        Now I’ve this for both platform but iOS doesn’t play the sound.
        var filePath = cordova.file.applicationDirectory + “www/mp3/sound.mp3”;

        • When you print cordova.file.applicationDirectory to the logs, what does it return? (ios)

          • Bryan Villafañe

            file:///private/var/mobile/Containers/Bundle/Application/TONS-OF-NUMBERS/Myapp.app/

          • Just to confirm, using var filePath = cordova.file.applicationDirectory + “www/mp3/sound.mp3”; what is the error you get in your logs for iOS? If it doesn’t play, there should be an error message.

            The path seems correct though.

            Regards,

          • Bryan Villafañe

            Unknown resource ‘file:///private/var/mobile/Containers/Bundle/Application/TONS-OF-NUMBERS/Myapp.app/www/mp3/sound.mp3’

          • Bryan Villafañe

            I got it.. It’s just “mp3/sound.mp3”

          • Awesome! I’m glad you figured it out 🙂

          • Soumalya Gan

            I am still getting unknown resource. Please help

  • Christian

    Thanks a lot for sharing this, Nic.

    I followed your tutorial step by step (also watched the video to be sure to replicate your steps 100% accurately), however I always get ” Uncaught ReferenceError: Media is not defined”. Could it be that the cordova media plugin is somehow not compatible with phonegap or ionic anymore?

    Here is the code I’m using, I believe it’s exactly the same as in your tutorial here: http://jsfiddle.net/unrrncwe/

    I also definitely installed the plugin and added the platforms.

    Do you have any hint why I’m getting this error, can anyone reproduce it?

    Thanks a lot for your help!

    • Did you install the platforms before the plugin? If you didn’t, the plugin may not have installed correctly. Regardless, try to reinstall the plugin because sometimes they get corrupt.

      Also, please confirm that you’re not trying to test in a browser. It needs to be built to binary and installed to device or simulator.

      Let me know if that works.

      Regards,

      • Christian

        I removed and reinstalled the plugin, unfortunately without success.
        I unfortunately just can test in the emulator, I’m receiving

        Error: undefined is not a function (evaluating ‘$cordovaMedia.play(media)’) there :(.

        I really appreciate your help Nic!

        • I just consulted the documentation:

          http://ngcordova.com/docs/plugins/media/

          Looks like they did a full rewrite of this module recently (after I wrote this guide). Looks like I’ll be updating this guide in the very near future.

          Let me know if you can’t figure out the official docs.

          Regards,

          • Christian

            Thanks for the link Nic, I’m fairly new to Cordova/Ionic and haven’t known this one yet. It actually works now, although I had to put my code outside the .then-function which doesn’t work I think, but maybe I got something wrong.

            However, your tutorial is still very useful, wouldn’t have known about the different android path for instance. Thanks a ton for helping me out and being so kind to share your knowledge here, I’m looking forward to your next post!

          • I sent an inquiry to the ngCordova project maintainer asking for an improved strategy for breaking changes made to the project. Since there are no clean versioning rules, it is hard to manage these events.

            I’ll report back when I get a reply.

            Regards,

  • Oak Krittee

    how to play again after $cordovaMedia.pause(media);
    thank you.

  • Anjum

    Many thanks Nic for a valuable guide. I watched your video twice and followed all the steps from scratch. But my media won’t play. I did the ADB logcat which I also learnt from your comments. Below is what I get when I press the Play Audio button. You help will be much appreciated. Thanks

    E/SoundPool( 385): error loading /system/media/audio/ui/KeypressInvalid.ogg

    W/AudioService( 385): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg

    W/AudioService( 385): onLoadSoundEffects(), Error -1 while loading samples

    W/SurfaceFlinger( 49): couldn’t log to binary event log: overflow.

    W/PluginManager( 2308): THREAD WARNING: exec() call to Media.create blocked the main thread for 850ms. Plugin should use CordovaInterface.getThreadPool().

    D/CordovaLog( 2308): file:///android_asset/www/lib/ionic/js/ionic.bundle.js: Line 19387 : TypeError: Object # has no method ‘play’

    D/CordovaLog( 2308): at Scope.$scope.play (file:///android_asset/www/js/app.js:28:23)

    D/CordovaLog( 2308): at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:20124:18)

    D/CordovaLog( 2308): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50863:9

    D/CordovaLog( 2308): at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22178:28)

    D/CordovaLog( 2308): at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22276:23)

    D/CordovaLog( 2308): at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50862:13)

    D/CordovaLog( 2308): at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10823:21)

    D/CordovaLog( 2308): at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2811:7)

    D/CordovaLog( 2308): at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2800:3)

    D/CordovaLog( 2308): at HTMLDocument.tapTouchEnd (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2918:5)

    I/chromium( 2308): [INFO:CONSOLE(19387)] “TypeError: Object # has no method ‘play’

    I/chromium( 2308): at Scope.$scope.play (file:///android_asset/www/js/app.js:28:23)

    I/chromium( 2308): at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:20124:18)

    I/chromium( 2308): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50863:9

    I/chromium( 2308): at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22178:28)

    I/chromium( 2308): at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22276:23)

    I/chromium( 2308): at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50862:13)

    I/chromium( 2308): at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10823:21)

    I/chromium( 2308): at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2811:7)

    I/chromium( 2308): at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2800:3)

    I/chromium( 2308): at HTMLDocument.tapTouchEnd (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2918:5)”, source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (19387)

    D/LightsService( 385): Excessive delay setting light: 471ms

    • Few questions and please answer all of them:

      Are you testing in a web browser or a device / simulator?
      Are you sure that /system/media/audio/ui/KeypressInvalid.ogg exists?
      Are you sure your device can play ogg format files?
      Are you using the version of ngCordova that I’m using?

      Regards,

      • Anjum

        Thanks for your quick turn around 🙂
        1. I am testing in a simulator
        2. I never put that ogg file anywhere. I simply followed the steps in your video. Nothing less nothing more. I created a fresh project just to ensure that nothing is different from your setup.
        3. I am not trying to run an ogg file
        4. I don’t know. I downloaded the latest version a couple of hours back.

        • I am not using the latest version in my tutorial. Because ngCordova is alpha, breaking changes can be introduced at any moment in time until it is no longer alpha / beta. I am using this version:

          https://github.com/driftyco/ng-cordova/archive/9f907a654b3f27dcf9070d116df1963df297593e.zip

          Breaking changes were in fact introduced in more recent versions. I will rewrite the tutorial when we have a stable release.

          Based on your response, I’m going to assume the ogg file is an error unrelated to what you’re trying to accomplish. Try using the version I used and see if you get better luck.

          Regards,

          • Anjum

            Thanks Nic,

            I appreciate your help and would look forward to see the rewritten tutorial. But on the other hand do u think it would be a good idea to use ngCordova for a production App? I already have my App on Android Store with over 50k downloads but that is written in JQuey + Cordova. I wanted to move on to a better platform like AngularJS + Ionic which landed me here 🙂

          • I use ngCordova and Ionic in my production apps.

            Ionic is still beta and most Cordova plugins are open source, so there will be a level of risk even beyond ngCordova. Do thorough testing on if what is available meets your needs and make a determination from there.

            You can use an older version of ngCordova without issue (example, for audio). ngCordova is so large, most of the changes are new features. Being that it is just a wrapper for Cordova plugins, you can even pick and pull what you need in your project.

            Hope that makes sense.

          • Anjum

            Oh yes, ionic is also beta 🙁

            Many thanks for your advice. I will test this hopefully tomorrow as its already midnight here. Good bye!

          • Anjum

            Thanks Nic. I was able to play Audio with your version of ngCordova. You may wish to update your post and highlight this point, so that people don;t use the wrong version. Many thanks once again. I will move on to building the Audio Player. BTW can the same be used for all sort of media, like Videos also?

          • To my knowledge $cordovaMedia is only for audio if that’s what you mean.

  • zhnl

    Hi Nic,

    Thanks for guide. I have a problem with ionic is that I achieve to play audio but when my application goes back to stack audio still plays. How can I manage this. Thanks.

    • Are we talking about Android or something else? Please give me more information on your setup and what you’re doing.

      Regards,

      • zhnl

        I am talking about android platform. When I use hardware back button audio stops but when I press any other button and send application back to start another one audio plays like a service. My setup is same as you.

        Regards.

        • Can you put your project on GitHub? I’ll take a look at it if you put it up.

          Regards,

          • zhnl

            Hi Nic,

            This is not full code but service controller and view all in this. https://github.com/hozhanli/IonicVideo

            My main purpose is play video coming from api.
            Could you help please..

          • zhnl

            In reality I achieve play video without Cordova media plugin but I cannot control its play as a service. I versioned github and I don’t know how to stop video play as a service.

            https://github.com/hozhanli/IonicVideo

            Thanks.

          • Let’s step back a bit.

            I can see you’re trying to work with other things as well (video, etc.). For purposes of learning and experimentation, please create a new project and follow my tutorial exactly. This will help rule out bugs in your code vs fault from possibly incorrect information in the tutorial.

            As for videos, this is a different topic and should be addressed in the forums.

            Regards,

  • Is there any way to get the audio to start playing while the mp3 is downloading from a remote server? I noticed that it doesn’t appear to stream, but instead locks up the app until the mp3 has finished downloading.

    • You may want to post this question to Apache and see if there is an undocumented buffering method. Otherwise you may have to develop your own chunk logic to download the files in pieces.

      Regards,

    • Martin Spriggs

      Daniel, did you ever figure out how to resolve this iOS blocking issue?

  • Bunchuu

    Hi Nic, excellent tutorial but I have a problem, when I add the line to my index.html my project crash with this error:
    Unknown provider: $cordovaActionSheetProvider <- $cordovaActionSheet. I dont know whats wrong. Thanks.

    • Being that your error is related to the action sheet, it seems that you have other problems.

      You may want to post this question in the forums. I’d like to keep this question board strictly on the topic of audio.

      Regards,

  • sooz

    Hi Nic, I tried your tutorial and I apply different change for my usage..

    I see that if I use the external mp3 (of internet) its work but if I use the internal mp3 didn’t works, why?

    I have my app in this tree example:

    root

    — www

    — index.html

    — mp3

    — templates

    ok?

    now I do this

    app.js

    angular.module(‘starter’, [‘ionic’, ‘ngCordova’, ‘starter.controllers’])

    ….some code

    .state(‘app.browse’, {

    })….some code

    in controllers.js :

    angular.module(‘starter.controllers’, [])

    .controller(‘SoundCtrl’, function($scope, $cordovaMedia) {

    //Play a media

    $scope.play = function(src) {

    };

    })… some code

    in my browse.html:

    its don’t work, if i do

    don’t work again, I have in my browse.html an image I load it in this way

    and its works…. why the image work and the local mp3 audio doesn’t workk??

  • sooz

    Hi nic, I solved my problems… now I have a question:
    I have an image-map ( ) in the are different tags, if I click an area must start to play a sound.
    If I play more time different sounds after 10 / 20 time the app stop to do sounds and I must close and reopen it to play other sounds.
    Why?
    Can I clean the cache of the sound that I play?

    • Sorry, but I’m having trouble understanding what you’re trying to describe. Can you please try again?

      Regards,

  • Guest

    Hi Nic, Thanks for the tutorial. Could you please explain how I could change system audio volume level from ngCordova?

  • SubjectiveEffect

    I’ve done exactly what you’ve done and I’m triggering it with an an ng-Click. The error I get is “$cordovaMedia.play is not a function”.

    • Can you please share your full logs and put your code on GitHub please?

      Regards,

      • SubjectiveEffect

        I don’t want to post if on GitHub as it’s part of the new version of one of my published apps. The only difference I can imagine is that the controller is in a different file to app.js (it’s in controllers.js) and I haven’t used device ready, although you haven’t either. Its on the ngcordova site though.

        • I understand you’re hesitant about posting your project on GitHub, but if I can’t see the code and your full logs, I won’t be able to help you.

          Sorry,

          • SubjectiveEffect

            I’m sure it’s something simple. The error in Chrome inspect is: “Uncaught ReferenceError: $cordovaMedia is not defined”

            This is as if the plugin isn’t installed or initialised, yes? You don’t put your code in device or ionic ready function. Are you supposed to?

          • Testing in Chrome leads me to believe you’re trying to test in your web browser. Native device plugins will not work in a web browser.

            If you’re trying to manage audio on load it should be in a device or ionic ready. You should be fine if you’re handling it with button press since more than likely it would have been loaded by then.

            Regards,

          • SubjectiveEffect

            I’m testing it with ionic run android on a USB connection. You can use Chrome inspect to debug it on the phone. I’ve installed and used many device plugins before, like Google Analytics, Native Alerts, Email etc so I know how it works.

            The only thing I’ve done different this time is not put the code in the $ionicPlatform.ready function, but as I’m using Ionic and thus angular I really need it in the controller don’t I? It gets called by a button press. Perhaps the plugin hasn’t installed properly…

          • Yea it is good practice to keep Apache Cordova plugins inside of an onReady of some sort. Maybe try removing and re-installing the plugin?

            Another possibility is maybe the plugin changed since writing the tutorial. Are there any open issue tickets for the developer?

            Regards,

          • SubjectiveEffect

            The plugins I call from app.js in the onReady seem to work fine. The plugins I call from the view controllers don’t.

            I’m trying to keep my code readable so I have different .js controller files. All the plugins called in them seem to not be functional. I’m including ngCordova as a dependency in the controller modules so I don’t get why it’s not working.

          • Yea I don’t know. If I can’t see it, I can’t help.

            Sorry,

    • Paolo Marrone

      The $cordovaMedia.play method doesn’t exist anymore. Use instead:

      var media = new Media(…);
      media.play();

      About the file name, if you use a local file, on Android you must add ‘/android_asset/www/’ before the file name:

      if (ionic.Platform.isAndroid()) src = “/android_asset/www/” + src;

      Hope this helps

  • Osama Haj

    Hey Nic, I am having an issue with pausing the file, please help!
    . https://github.com/oah24/bismillah/blob/master/www/js/app.js

    • Osama Haj

      Hey Nic, I guess you did not get a chance to look at my code yet?

      • Sorry, I’ve been very busy and have not yet had a chance to look. I’ll try to look this week.

        Regards,

        • Osama Haj

          I wanted to ask you if you can develop some apps for me, I have a few projects in mind. I am willing to pay. Let me know if you are interested.
          Thanks,
          Osama

          • Any comments or questions not related to my article should be directed at my Twitter @nraboy.

            Thanks,

    • Should be inside your controller and also inside an $ionicPlatform.ready or onDeviceReady method.

      • Osama Haj

        Hey Nic, I have updated the file on GitHub, I still can’t get it to pause. Can you tell me What I am doing wrong? Thanks

        • You’ve made the my_media variable local to the play function again.

          You may want to take a step back and do some reading on AngularJS and JavaScript.

          Regards,

          • Osama Haj

            I have tried placing that line in $ionic.Platform. ready and still didn’t work

  • 朱琳

    I just want to say thanks for this blog, but it doesn’t work for me , I follow this issue below, find loicknuchel
    ‘s way is worked for me .Hope you will update this blog.

    Really thanks for your sample at last ^ ^

    http://forum.ionicframework.com/t/how-to-play-local-audio-files/7479/3

    • Can you please provide error logs? If there truly is a problem with my article, I can’t fix it unless I know what isn’t working.

      Regards,

  • Anil Kumar

    Hey Nic,
    The audio player is still playing , while i am getting a call or message, I need to pause the audio player automatically while getting a call and resume it automatically like a natural audio player app in the mobile,
    can you suggest me what I have to do for this one

    Thanks and Regards
    Anil Kumar B

    • Handling calls and messages is a completely different topic that I know nothing about. I’m sure there are plugins for it, but I’ve not used any.

      Sorry

    • Andy

      You could handle your app-lifecycle by your own and set your media object to pause if your app is switching to inactive mode. See here for more information: http://docs.phonegap.com/en/1.6.0/cordova_events_events.md.html#resume

      • Thanks for sharing this information 🙂

  • tit0 blaze

    Any idea on how to fix the “Media is not defined at $scope.play” error. I followed step-by-step and have no idea how to get around this (very helpful blog btw). An update to the article may be useful for others stumbling upon this blog as well

    • Please paste your full error logs.

      Regards,

    • Luis Troya

      Check ngCordova is added as dependency in your project

  • Anil Kumar

    Hi Nic,
    Can you please tell me the above program will work for windows platform? I tried for windows but it is not working for me 😉

    Regards
    Anil Kumar

    • The Windows platform is not officially supported by Ionic Framework. Being that I am a Mac user, I have no way to test and determine whether or not this or anything else Windows will work with Ionic Framework.

      Regards,

  • Zane Goh

    Hi Nic, I couldn’t get this work for both iOS and Android, is there any mistake I made? I didn’t get any errors but only no sound for both device. I am sure that I followed your video accordingly.

    • If you truly have no errors (99% you’re going to have errors), then maybe it is a bug with the plugin. You may contact the plugin developer and see whats up.

      Regards,

      • Zane Goh

        Hi Nic, thanks for your quick response, I found out there is actually not a bug, there’s an issue with the file directory. By the way, I was planning to get the media from URL not local file, so I found out another solution for this. Thank you so much.

        Regards.

        • Thanks for reporting back 🙂

          Mind linking to your other solution in case others have the same question?

        • Mohamed Dahmane

          hi, if you could share your solution, I have urls for live streaming with .acc extension not working with this tuto
          Thank you

          • My guess is .acc is an unsupported audio type for many devices. Regardless, any time I hear “not working” I’m going to ask you to paste your logs.

            Regards,

  • Hi, thanks for posting this! 🙂 Does the media plug in allow for playing audio on Android and iOS while the app is in the background (user navigated to another app or minimized it).

  • Yamael

    Hi, Thanks for the tutorial 🙂 I found your blog when I search a solution to my problem… I have the famous “”Error: Media is not defined” bug. Can you help me to solve this ? thanks

    controllers.js

    angular.module(‘starter.controllers’, [‘ngCordova’])

    .controller(‘AppCtrl’, function($scope, $cordovaMedia, $ionicLoading, $ionicModal, $timeout) {

    $scope.playOgg = function(src) {
    var mediaOgg = $cordovaMedia.newMedia(src);
    mediaOgg.play();
    };

    html

    • Please paste your full logs.

      Regards,

      • Yamael

        my reply detected as spam 🙂 check this.

  • Hridaya Kandel

    so much useful link.. can you give me best way to use multiple button for multiple file in server and play these files when user click on one of them.. i want to make ng-repeat on this as
    Play from internet i am not sure if above works or not.

    • Remove the curly brackets:

      ng-click=”play(‘someurlhere’ + audio.name)

      Regards,

      • Hridaya Kandel

        thankyou

  • Hi, nice tutorial Nic. I followed your other tutorials too. But here I am facing some issue. I have done whatever you told here. Here is my code:

    Boro Asha kore

    Controller:

    angular.module(‘starter.controllers’, [‘starter.services’, ‘ngCordova’])
    .controller(‘BasicCtrl’, function($scope, $ionicActionSheet, $timeout, $ionicBackdrop, $cordovaMedia, $ionicLoading) {
    $scope.play = function(src) {
    var media = new Media(src, null, null, mediaStatusCallback);
    $cordovaMedia.play(media);
    };
    var mediaStatusCallback = function(status) {
    if (status === 1) {
    $ionicLoading.show({template: ‘Loading…’});
    } else {
    $ionicLoading.hide();
    }
    }
    });

    When I tried in browser I was getting this error: “Error: Media is not defined”. Then I tried in android emulator. Here also audio didn’t played. And I am unable to check the error logs. Could you please help me out. Thanks.

    • Thanks! Thanks!.. It’s working fine. Earlier I checked with android studio emulator. There I was facing this problem. Then I have downloaded gennymotion. It works fine here. Audio plays perfectly.

      But need some more help.
      i) When I closed the app, audio stopped. I don’t want to stop the audio until and unless user press the stop/pause button.
      ii) How to integrate seek bar and volume bar. (any suggestions)

      Thanks once again 🙂

      • I believe there is an option you can pass for playing audio in the background. You should refer to the plugin documentation.

        In regards to a seek bar and any other styling, you should consult the Ionic documentation or ask in the forums. My design skills are not the best.

        Regards,

  • Krazzie KAy

    I did exactly the same process as far as I believe, but on clicking the button nothing happens!! That loading.. also doesn’t show up, can u help me?

  • William Wong

    How do I release the underlying OS’es audio resources?

    Source code as follows:

    in services.js

    .factory(‘MediaSrv’, function($q, $ionicPlatform, $window){

    var service = {

    };

    function loadMedia(src, onError, onStatus, onStop){

    }

    function _logError(src, err){

    }

    function getStatusMessage(status){

    }

    function getErrorMessage(code){

    }

    return service;

    })

    IN CONTROLLERS.JS
    var createTrain2 = function(train2) {

    }

    PLEASE HELP

    • How about instead of throwing a ton of code at me (which I don’t approve of), you tell me in more detail what you’re trying to accomplish and what isn’t working.

      Regards,

      • William Wong

        Sorry for bombarding you with code without context. When a button is pressed, a sound plays. After being pressed 20-30 consecutive times, the sound stops playing. Below are the log files:

        09-03 09:21:48.075: V/AudioSink(247): AudioOutput(52)

        09-03 09:21:48.085: V/AudioPolicyManagerBase(247): Offload denied by duration < default min(=40)

        09-03 09:21:48.104: D/AudioPlayer(2116): Send a onStatus update for the new seek

        09-03 09:21:48.104: V/AudioSink(247): setVolume(1.000000, 1.000000)

        09-03 09:21:48.114: V/AudioSink(247): setAuxEffectSendLevel(0.000000)

        09-03 09:21:48.114: I/AudioPlayer(247): seekTo time_us (0)

        09-03 09:21:48.114: V/AudioSink(247): flush

        09-03 09:21:48.154: I/AudioPlayer(247): Audioplayer kKeyAudioPCMFormat:1, 1, 0

        09-03 09:21:48.154: I/AudioPlayer(247): Audioplayer kKeyAudioPCMFormat read fail(1, 1)

        09-03 09:21:48.154: V/AudioSink(247): open(44100, 1, 0x0, 0x1, 4, 52 0x40000)

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): getOutput() device 2, stream 3, samplingRate 0, format 0, channelMask 3, flags 0

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): getOutputsForDevice device 0002 -> 0002

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): selectOutput() output 2 outputDesc->mProfile->mFlags 0002 flags 0000

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): selectOutput() output 3 outputDesc->mProfile->mFlags 0004 flags 0000

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): getOutput() returns output 2

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): getOutput() device 2, stream 3, samplingRate 0, format 0, channelMask 3, flags 0

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): getOutputsForDevice device 0002 -> 0002

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): selectOutput() output 2 outputDesc->mProfile->mFlags 0002 flags 0000

        09-03 09:21:48.154: V/AudioPolicyManagerBase(247): selectOutput() output 3 outputDesc->mProfile->mFlags 0004 flags 0000

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): getOutput() returns output 2

        09-03 09:21:48.164: V/AudioSink(247): no track available to recycle

        09-03 09:21:48.164: V/AudioSink(247): creating new AudioTrack

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): getOutput() device 2, stream 3, samplingRate 44100, format 1, channelMask 1, flags 40000

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): getOutputsForDevice device 0002 -> 0002

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): selectOutput() output 2 outputDesc->mProfile->mFlags 0002 flags 40000

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): selectOutput() output 3 outputDesc->mProfile->mFlags 0004 flags 40000

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): getOutput() returns output 2

        09-03 09:21:48.164: E/AudioFlinger(247): no more track names available

        09-03 09:21:48.164: E/AudioTrack(247): AudioFlinger could not create track, status: -12

        09-03 09:21:48.164: E/AudioSink(247): Unable to create audio track

        09-03 09:21:48.164: V/AudioPolicyManagerBase(247): releaseOutput() 2

        09-03 09:21:48.164: D/AudioPlayer(2116): on completion is calling stopped

        09-03 09:21:48.164: D/AudioPlayer(2116): on completion is calling stopped

        I read on StackOverFlow that you have to release the underlying OS’es audio resources after the sound stops playing. If you don’t, there will not be enough memory for additional audio play. Thanks in advance

        • I don’t think you can control how the application handles resources in the operating system. Android and iOS should free them up as necessary.

          Playing your audio 30 times inside your own application sounds all kinds of bad. You should check to see if the media is loaded / playing before trying to do it again.

  • Rajesh Kumar

    Hi Sir,

    It’s giving an error can’t find Media variable.

    Can please help me out ?

  • Oak Krittee

    HI.Mr.Nic
    I create new project and i add plugin > cordova plugin add cordova-plugin-media
    and follow your code. but error (onclick nothing happen)
    error > “exec() call to unknown plugin: Console”

    please help me. thank you

  • Sab

    Hi Nic,

    Thanks for the great blog

    Would like to create a playlist. Is there a way to create and play a playlist. Can you please suggest a solution.

    • You would have to add your own logic to create one. For example, storing song meta data as well as location in local storage or similar and populating a list view when someone wants to see the playlist.

      Regards,

  • Stevie Starosciak

    Hello again, dear friend.

    I’ve gotten the ngCordova media plugin to work in my app on my ios emulator, using an external URL to play the audio file…however, I’m trying to build some functionality where basically you download the mp3 from an external source, save it to your device, and then play the file from there. I can’t seem to get it work, even though I can verify that the file does exist. Here is my code:

    $scope.playAudio = function() {

    document.addEventListener(‘deviceready’, function () {
    var src = cordova.file.dataDirectory + fileSrc;
    //var src = ‘http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2013.mp3’;
    var media = $cordovaMedia.newMedia(src);
    var iOSPlayOptions = {
    numberOfLoops: 2,
    playAudioWhenScreenIsLocked : false
    }

    And for the record, I’m running into this issue, as well, when I try to utilize an mp4 file on my device, in order to play videos.

    I’m running “ionic emulate ios”, so I’m not entirely sure why reading from the device would be problematic. Am I missing something? Thanks dude!

    • What do your logs say? Any time you say something isn’t working, it is the first and only thing I’m going to ask for. Applies to everyone 😉

      • Stevie Starosciak

        That is completely fair haha. But seriously this time…I’m not getting any errors or anything…which is why I’m asking what maybe you’ve seen the problem to be :/

        I click the button associated with that playAudio and it does nothing. I console.log the src for the URL in the terminal and i get this:

        file:///Users/Stevie/Library/Developer/CoreSimulator/Devices/70EA2E87-A715-4252-B5B8-A5C03E090BD9/data/Containers/Data/Application/36939341-AB15-480A-86F7-869A917B86AC/Library/NoCloud/resources/resource-1/resource-1.mp3

        And then of course, just for safe measures, here is the media object from $cordovaMedia

        {“media”:{“id”:”9485a8ff-8c69-a950-fe1c-8001483889eb”,”src”:”file:///Users/Stevie/Library/Developer/CoreSimulator/Devices/70EA2E87-A715-4252-B5B8-A5C03E090BD9/data/Containers/Data/Application/36939341-AB15-480A-86F7-869A917B86AC/Library/NoCloud/resources/resource-1/resource-1.mp3″,”_duration”:-1,”_position”:-1}}

        That’s the best I can do for logs, unfortunately as nothing is throwing an error 🙁

        • It fails on both iOS and Android? Have you tried on an actual device? I’m wondering if the iOS simulator has sound issues.

          Also, what version of Xcode and iOS are you using?

          • Stevie Starosciak

            I haven’t actually tried on an actual Android device, which was gonna be my next step. The thing is…I can get the audio player to play when the URL comes from an external source, such as http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2013.mp3

            but it’s just when I try to load the src of the file from my device does it just sit there and do nothing. I’ve had the same problem when trying to utilize a separate mp4 file as the source for a . I really think it’s something weird going on with the file system, but not entirely sure what.

            I’m currently using xCode 7.0.1 and iOS 9 I believe

          • Based on all the information you provided it seems like it should work. I’m wondering if iOS 9 introduced security restrictions beyond ATS (which is a nightmare) that prevents certain access to the filesystem. I wouldn’t be surprised.

            Let me know if it works on Android.

          • Stevie Starosciak

            Heh, yep. So, yes, another instance where stuff works on the actual device, but not necessarily the simulator…which…I’m starting to realize that if you know you’re gonna be doing any testing that requires cordova…just always default to using an actual device. These emulators and simulators are just terrible. All of them. Haha I know you’ve said that before, but do you typically do as much as you can in the browser, but then do all your testing on actual devices?

            Please forgive my ignorance.

          • I only test in the browser if there are no plugins included in my application. Meaning I only test UI functionality. Once you start introducing plugins, the browser becomes worthless.

          • Stevie Starosciak

            Oh most definitely. What’s weird is that some plugins work with “ios emulate ios -lcs”, where as some only work with “ios emulate ios”. Others don’t work at all, so it would appear that the safest bet is to just use the actual device always and forever haha

          • Stevie Starosciak

            Alright man, I think there is just an issue with iOS 9 not being able to play audio or video files from the local device. I’ve tried everything. I can even play an audio file from the app’s www folder, but I can’t play an audio file from the file storage of an iPhone device.

            Though this all works on Android no problem, do you know of an alternative where the file could be opened up by a preferred app on the user’s device? I was able to accomplish this with a PDF file that gets downloaded to the device, so I have no idea if it’s the media plugin or something is completely jacked up when trying to access any type of video or audio file on an iPhone device 🙁

          • iOS 9 has a mess of problems with Apache Cordova apps. You might open an issue ticket for the plugin developer.

            Best,

          • Damien Fourcade

            Same issue on my side and solution founded for IOS :

            var media = $cordovaMedia.newMedia((cordova.file.documentsDirectory + src).replace(‘file://’, ”));
            media.play();

  • Federico Pasinetti

    I apologize for my bad English but i’m italian and i don’t speak english very well.

    I have a problem with audio player, is very slow to start on iOS (not on android).

    THIS IS MY CODE:
    PlayerLiturgia.play = function() {
    $scope.state = ‘loader’;
    function mediaStatusCallback(status) {
    if (status == 0) {
    console.log($scope.state);
    }
    if (status == 1) {
    $scope.state = ‘loader’;
    }
    if (status == 2) {
    $scope.state = ‘play’;
    }
    if (status == 3) {
    $scope.state = ‘pause’;
    }
    if (status == 4) {
    $scope.state = ‘pause’;
    }
    };
    if (media == null) {
    media = new Media(src, null, null, mediaStatusCallback);
    console.log(‘media != null’);
    }
    media.play();
    console.log(‘media.play()’);
    };

    When i tap play button, audio don’t start, it start after a 10/15 seconds, while on Android it start immediately.

    Why?
    Thank you for help.

    • What do your logs say? What version of iOS? What version of Apache Cordova?

      The more information you give me, the better I can help you. No code please. Never post code unless asked please.

      Regards,

      • Federico Pasinetti

        My logs do not say anything, simply stop and wait.
        I use iOS 9.1 and conrdova 5.1.1.
        Sorry for posting the code, i didn’t know.

        • I heard other people reporting this with iOS 9. You might post an issue ticket with the plugin developer. There may be a permission issue preventing it from working that Apache needs to fix.

          • Federico Pasinetti

            Ok thank you.

  • markbbishop

    Can you use {{getting.mp3}} instead of the full URL if I’m simply fetching json data through a controller?

    • That depends:

      I don’t know what you’re trying to represent with {{getting.mp3}} or where you’re trying to use or represent it
      I dont know what JSON data you’re getting

      Regards,

      • markbbishop

        I’m getting wordpress posts through a controller, then I created a custom json called listen. The output shows:
        listen: “http://stream.song365.me/h1/20151101/1772589959/Chevelle%20-%20Twinge_(song365.cc).mp3”

        So it’s just a mp3 URL.

        Then in my HTML, I have:

           LISTEN

        • I don’t see why it wouldn’t work. What’s the issue?

          • markbbishop

            It gives a blue line under the text to show its a link, but I click it and nothing happens. Do I need to install Cordova media plugin for this to.work?

          • Of course you need the plugin. My tutorial shows this with remote links just like how you’re trying.

  • Geroen Joris

    Hi Nic, just a quick remark: the $scope.play method in your code is no longer correct, I assume due to a changed API. $cordovaMedia doesn’t seem to have a play method anymore; according to the docs, you have to create a newMedia, and then call play on it.

    For your article, instead of:

    $cordovaMedia.play(media);

    … it should actually be:

    media.play();

    And that kind of eliminates the need of $cordovaMedia. I myself reverted to using the cordova plugin directly, as opposed to using $cordovaMedia, which is too limited anyway.

    You could also rewrite your code as:

    $scope.play = function(src) {
    var media = $cordovaMedia.newMedia(src);
    media.play();
    }

    … but you wouldn’t have any access to the callbacks anymore. Which, for me, was the reason to switch to using the cordova plugin directly. $cordovaMedia is simply too limited at this point.

    • I hear you.

      I regret ever using ngCordova in my tutorials. It can’t keep up with the cordova base plugin. Thanks for sharing what you found 🙂

  • Anil Kumar

    Hi Nic,
    In media plugin can we play an m3u file’s I tried in an sample project it throw’s an error with a code of 1 .
    Do you have any idea how to play an m3u file in Ionic Framework

    • To my knowledge m3u files are playlist files and I don’t think this plugin will be able to play them.

      Best,

  • Federico Pasinetti

    Hi Nic,
    If i would play a two audio in sequence in background on iOS how can i do?

    If i play only one audio i background the plugin work fine, but if i try to play 2 audio in sequence, the second don’t start, why?
    while it works fine on android, have to add anything else on iOS?

    I tried this plugin https://github.com/AubreyHewes/cordova-background-audio but dosen’t work.

    do you have any idea?

    Thank you

    • What do your logs say?

      • Federico Pasinetti

        Nothing

        • How are you checking your logs?

          • Federico Pasinetti

            With safari inspector or xcode logs

          • Federico Pasinetti

            If i install app from xcode on device the player work fine, but if i upload the app in testflight on itunesconnect and test app frome testflight doesn’t work. Do you know why?

          • I don’t use TestFlight so I don’t know. Sorry,

  • Adebisi Olaoluwa
    • You’ll have to scan your device using the File plugin for audio files. Audio files that are found should have their meta data stored in SQLite or whatever database you’re using. Then your UI will be based around the database which points to the actual song location in which case you can choose what to do.

      I don’t offer private help through email, sorry.

  • Gunasekhar

    Hi Nic, I am adding media plugin but it is showing “Plugin doesn’t support this project’s cordova-android version. cordova-android: 4.1.1, failed version requirement: >=5.0.0-dev”, can you help me how to play in Android o.s < 5.0.0

    • Cordova Android is not the Android OS version. You need to update the Android platform in your project. This is not the same as updating your Cordova CLI.

  • Stevie Starosciak

    Hey Nic, I’m working with the cordova media plugin again and I’m trying to build an audio player that doesn’t use HTML 5’s audio player (so I can play audio when the screen is locked). The problem is that the Media object can’t seem to determine what the duration of the mp3 is.

    So I have a media object that looks like this:

    {“media”:{“id”:”ae7cd94a-502e-0b4d-0648-7f628432f498″,”src”:”cdvfile://localhost/library-nosync/resources/resource-1/resource-1.mp3″,”_duration”:-1,”_position”:-1}}

    I try to run both $cordovaMedia.getDuration() of the file and across two different mp3s, it returns a -1. Is there something I’m missing here?

  • Jorge Andres Moreno

    thanks for posting , I have a question if I want another pause button ? how I do

    • What do you mean, another pause button?

      • Jorge Andres Moreno

        make a button to pause audio, you have play(), but i want pause the audio

        • Just call the pause function?:

          http://ngcordova.com/docs/plugins/media/

          I’m confused on the issue.

          • Jorge Andres Moreno

            jejej in the same button i make media.play() and media.pause(), but It worked
            is this (Sorry for the public code):

            var playing = false;

            $scope.play = function(){
            if (playing == false){
            media.play();
            $scope.class = “ion-ios-pause-outline”;
            playing = true;
            }else{
            media.pause();
            $scope.class = “ion-ios-play-outline”;
            playing = false;
            }
            }

            it was easy…

          • Steve Bissoué

            Jorje please the full code

  • Bill Rousseau

    Hello,

    I’m trying to build this app on my Android device, but sound does not play.

    I added some permissions that seem required (android.permission.WRITE_EXTERNAL_STORAGE, android.permission.RECORD_AUDIO, android.permission.MODIFY_AUDIO_SETTINGS, android.permission.READ_PHONE_STATE)

    but not workey. I tried to implement a success callback, it goes into but cannot play sound.

    Any ideas on this?

  • Abu Man

    hi niq, thanks for this article. it works on my android. I really appreciate if you can teach us to build streaming audio like radio apps or just give some basic ideas on how to do it..hehe btw thanks again, really helped me a lot.

  • SubjectiveEffect

    I just can’t get this working on iOS and no one on Stack Overflow can help either. At first I couldn’t get it working in my Android app but I was missing the “android_asset”.

    Of course I don’t (shouldn’t!) need this on iOS but I get no sound on iOS! The only difference between that and the Android version is the “android_asset”.

    Any help?

    • Anonamongoose

      Why should anybody help you? Judging by your comment history including your recent comment on techradar all you do is go about b!tching on articles that you’re right and everybody else is wrong all of the time. If you’re such an expert on matters then figure it out for yourself. Typical smart arse web commenter.

      • I appreciate you looking out for me here. Your intentions are probably good, but please let’s be nice to everyone.

        If this user is up to no good, I’ll deal with him.

        Best,

        • SubjectiveEffect

          Actually Nic, this guy is hounding ME. Whenever I see an error on an article I point it out. In this case it was a Techradar article that had the wrong date and my comment must have been seen because it’s been corrected. Anonamongoose barrelled in without know what had happen, got butthurt and has now deleted his comment, choosing to follow me to this, unrelated site.

          You know me anyway – I’ve read your stuff for a while since I use Ionic, and I’ve asked questions before.

    • I need more information. What version of iOS? What do your logs say? Device or simulator. Etc. Tell what you’ve tried without pasting code.

      Best,

      • SubjectiveEffect

        I’m using iOS 9.2.1.

        I’m building the app for development with XCode and deploying it to an iPhone 6. This is how I always test my Ionic apps (before testing on iPad and then in the XCode emulators). I don’t have any logs therefore.

        When building for Android I test it with a USB connection and Chrome Inspect. There are no errors in the console and the logs all work.

        I haven’t done anything different to the Android app, except take the assets bit out.

        • Xcode will still present you with logs

          • SubjectiveEffect

            Which bits do you need to know about?

          • SubjectiveEffect

            Ok, get this error.

            Unknown resource ‘/www/js/100bpm.wav’

            It’s definitely there though.

          • Are you sure iOS can play wav files? You might try a more common format like mp3 or mp4 just to rule it out.

            Best,

  • ramakrishnan

    hi Nic ,its working…thanks and plz try to update the plugin name and replace the line $cordovaMedia.play(media) with media.play();

    • Bla

      where did this “media” object come from please?

  • sheetal sharma

    i did same as you show in video, still i am getting error: “TypeError: $cordovaMedia.play is not a function”. what to do?

    • Anil Kumar

      Try with $cordovaMedia.play(media0

      • sheetal sharma

        i tried, still getting same error.

        • sufiyan khan

          run it in an simulator or in a mobile.I guess you are running it in browser by ionic serve.

          • Bla

            how do you test it if it’s in simulator?

  • Steven Quiros

    I have a Question, I could play the music on android, but now I want to create a new button for pause the song, Do i have to create another function in order to make that possible or Do I have to write the code in the same function? Thanks for the post!!

    • If you’re going to create a button you’re going to want a function for that button

      • Steven Quiros

        yeah, I’ve tried to add another function to pause, I did it exactly the same as the play function but instead of media.play(); I write media.pause(); but it didn’t work,do you know what might be the reason?? I’m new with ionic and cordova, sorry for the dumby question!! Thank you for the answer!!

  • Bla

    what could lead to the “Media is not defined” error?

  • Bla

    duh, this API is outdated, no one should be able to make it work.

  • Eze Sunday Eze

    i cant install the cordova media player plugin

    the error message is : error registry return 404 for GET on the repo link

    • Try this instead.

      cordova plugin add cordova-plugin-media

      Best,

  • Nitish Sharma

    I have also suffer from same problem my songs not playing in audio controls and its not showing……

    • What do your logs say?

      • Nitish Sharma

        no errors occur and i have songs played by the sites api’s but they can’t play songs

  • Samson Iyanda

    Hi, this works perfectly for me. However, I’m building an app in which audio play automatically as each slides swipe by. The question is what if I don”t wanna use a button to call play() function. I just want the audio to play when each slide passes by.

  • JV

    Hi Thanks for the post. Have experienced issues trying to play an mp3 file from a short url. I am experiencing the following when trying play the file this way – undefined:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found. Please assist. Thanks in advance.

    • I’ve not tried with short URLs, but I can imagine why this would be an issue. Short URLs redirect to the real URL and this is something the audio plugin probably does not account for.

      You should try to use the long, original URLs.

      Best,

      • JV

        Thanks the response. Much appreciated.

  • Fandy Chandra

    Hi Nic, is this tutorial still good? I follow your step to create online / streaming media player, but the media duration is not full loaded. for example, I load 3:47 duration but the player only show 3:14..

    • If it’s showing a time but it’s incorrect it is probably a bug in the plugin itself. You should open a ticket for the Apache Cordova plugin developer.

  • Vivek Pothagoni

    Hey Nic,

    Thanks for the post, I followed the instruction and created media player. In iOS everything is working. But on the android emulator there is no audio output. I know on Ionic serve it doesn’t work. Should I turn on any setting in the android emulator?

    How to play audio in the background of iOS and andriod?

  • Bruno Luis

    Hey man, thanks for the tutorial. it worked fine to me, but I have a question: What if I want to play two audios at the same time??

    something like this:

    in index.html

    Play

    in app.js

    $scope.play1 = function(src) {
    var media2 = new Media(src, null, null, mediaStatusCallback);
    $cordovaMedia.play(media2);
    }
    $scope.play2 = function(src) {
    var media2 = new Media(src, null, null, mediaStatusCallback);
    $cordovaMedia.play(media2);
    }

    Is it possible? I would really appreciate if you help me!

  • adedeji92

    Please i have implemented the above code and i will like to have the music controller(Next, previous and pause)
    to show in the notification bar for android devices. Any help??

  • Salman Ullah Khan

    I wanted to know if it is possible to play live stream audio using same technique?

    • adedeji92

      Yes

      • Salman Ullah Khan

        Can you please provide any example?

        • adedeji92

          If what you mean is playing songs from a server where the users can play the song with the use of internet then you can copy the URL to be source.

  • Shivang Pokar

    Hello Nic Raboy
    this music work in background mod application ?