Ionic - Playing an audio file on Android/iOS using Cordova media plugin


#1

Hello guys, I started building an app in Ionic for both iOS and Android. I need to play and record sounds in my app, so I first started to test how can i play sounds.
In order to do this, I used Cordova media plugin. I installed it, I created a js file to play a sound which looks like this:

function playAudio(url) {
    // Play the audio file at url
    var my_media = new Media(url,
        // success callback
        function() {},
            // error callback
            function(err) {}
        );

    // Play audio
    my_media.play();
}

I located the file in the www/js folder and linked it in the index.html. After that, I am simply calling the function from one of the templates using “onclick”.
Now, I know that this works since I tested it with an online URL and it proved to be fine. However, when I use a local URL, it doesn’t work, nothing is played.

I guess that my problem might be from the local url I provide: “sounds/Practice/heed3.mp3”, where the sounds folder is a separate folder inside the www one. I guess that this might be from the way Android uses the paths. Can you please help me?

PS: When building on Android I get the following message before the build happens, it might be related: “could not remove directory (code EBUSY) : C:\work\AppDev\CALVin\platfroms\android\assets\www/tempates”.

Thanks! :smiley:


#2

I have the exact same issue as well. Ok for online url but not ok for local url.
Saw many people asked the same question in this forum but still can’t find an answer.


#3

Hey.

I managed to fix this. Apparently on Android the path of the files is within android_assets/www.

So, you should try a link like “android_assets/www/your_url_within_the_www_folder”.

This worked for me. For ios, you can simply use the link as www/your_path.

Hope this helps. Cheers!


#4

Still can’t make it work:cry:
Below is the code I use for ios:

playAudio('/www/audio/msgSound.mp3'); // not ok

playAudio('www/audio/msgSound.mp3'); // not ok

playAudio('audio/msgSound.mp3'); // not ok

playAudio('/audio/msgSound.mp3'); // not ok

playAudio('http://res.cloudinary.com/dtj7y1r0l/video/upload/v1458851262/msgSound_x2laav.mp3'); // ok


#5

Actually I just tested it on Android so far. However, I am planning to use it for iOS too. As soon as I do this, I will come with an answer.
Until then, maybe you can post your code here. And make sure you have installed the media plugin :slight_smile:
Cheers!


#6

I don’t know if anyone’s having this problem, but the straightforward method of just calling “file://audio/chimes.wav” didn’t work for me, nor did 22 other syntaxes.

I finally got it working on an iPad using this method though:

Plugins used:
cordova-plugin-media
cordova-plugin-file

Cordova File location: ‘Project/www/audio/chimes.wav’

Code:

wavURL = ‘cdvfile://localhost/bundle/www/audio/chimes.wav’
$cordovaMedia.newMedia(wavURL).play()