How to play mp3 on Android using Phonegap Build

  • 1
  • Question
  • Updated 6 years ago
  • Answered
I want to know, how can I play mp3 audio file on Andoid using Phonegap Build?

I put my mp3 file in a folder, then using the tag to put it on my page but it is not playing.


<audio controls loop>
<source src="demo.mp3" type="audio/mpeg">
</audio>


Help!
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes

Posted 6 years ago

  • 1
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
I accomplish this using the media plugin, by adding the following line to my config.xml

<gap:plugin name="org.apache.cordova.media" />

Then I use the following code:



function mediaSuccess() {
console.log( 'mediaSuccess' );
}

function mediaError( errObj ) {
console.error( 'mediaError code=' + errObj.code +
' message=' + errObj.message );
}

function mediaStatus() {
console.log( 'mediaStatus' );
}

function createMedia( file ) {
if ( typeof Media != 'undefined' ) {
if ( (typeof device != 'undefined') &&
(device.platform == 'Android') ) {
file = '/android_asset/www/' + file ;
}
return new Media( file, mediaSuccess,
mediaError, mediaStatus );
}
else {
return file ;
}
}

function playSound( media ) {
if ( appPaused ) {
return ;
}
if ( typeof Media != 'undefined' ) {
media.seekTo(0);
media.play();
}
else {
console.log( 'playSound ' + media );
}
}

// preload sound files
snap_mp3 = createMedia( 'snap.mp3' );

// play sound file
playSound( snap_mp3 );

Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
delete the first three lines of the playSound method since appPaused will not be defined with this chunk of code.
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
but this is only for one mp3 file right? i have 10 mp3 sounds. so i must do this for each mp3? and also what about the pause, stop and loop button?

it will be great if i can get an index.html page example as well.
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
Of course, you're not going to define those functions again for each of the mp3 files. They are, after all, functions that can be called.

For the pause, stop and loop button, you create similar functions and call them accordingly. In those functions, you call the pause() and stop() methods as described in the plugin's documentation. For loops, you use:

media.play({ numberOfLoops: 5 }); // or whatever number you like
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
ok,so if i understand wel,I put my <audio> tag from HTML5 normal and then i put the media plugins in my xml file and then the function in javascript?
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
Well, you have several options:

1. Use the audio element, only (no media plugin required). You'd have to add event listeners, though. Something like [untested]:

<audio id="myaudio" controls="true">...

var anAudio = document.getElementById('myaudio');
anAudio.addEventListener('touchstart', function() { anAudio.play(); }, false);

The above code would use the html5 play() method of the audio element - which is different from the play() method of the media plugin.

2. Create your own audio player (no audio element needed) by combining a couple of graphics as you like, using the Media plugin and the functions as described above. Your custom buttons only need a click-eventlistener that calls the play, pause, stop functions respectively.
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
Ok, this is what I did and still not working:


<script>
var anAudio = document.getElementById('myaudio');
anAudio.addEventListener('touchstart', function() { anAudio.play(); }, false);
</script>



<audio id="myaudio" controls>
<source src="demo.mp3" type="audio/mpeg">
</audio>


I get only the default playe, when i click on the play button, not working. I removed the media plugin in my config.xml as well as you told me.

Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
Is your script performed before or after the audio element was inserted into the DOM? Did your script throw any javascript errors?
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
I am not sure if I understand the first part of the question. Well, the JavaScript codes are in the head section. The audio tag in the body section. No Javascript error. On PC it is playing, but on phone nope.
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
If your script is performed in the HEAD directly, the odds are, that the DOM is not complete, yet. So, your script will not be able to find the audio element. You should create a function of that piece of script and call it upon body.onLoad

That said, it looks like you'd be better off using the Media plugin.
From https://chrisgriffith.wordpress.com/2...

Although HTML5 does have an [audio] element, PhoneGap’s web view will not enable the audio to function. Instead we will need to rely on the Media API to do the actual audio playback.


[Thanks, Chris Griffith]
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
I still don't understand why Phonegap Webview does not support the audio tag. Why we have to put lengthy JavaScript codes just to play an audio.

And also,I have not understood the codes for media as well. If I get an index file with examples, i can understand it better. Or, if possible, you can help me writing the codes. If you can, here are some details.

-My mp3 files are in the folder where the index.html is.
-There are 10 mp3 files.
-There will be 4 buttons, Play, Pause, Stop and Loop for each mp3 file.

I have included the Media API in the config.xml again. Can you write the Javacript codes for me? Including the HTML. If I get only one FULL example,I will be able to understand. All the examples I have got on the web, are confusing.
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
Apparently, the WebView available with the latest Lollipop version of Android includes support for WebAudio. So the pain you are experiencing now should go away in a couple of years where the old versions of Android aren't being used. But for now, your stuck with needing a plugin.

https://www.infinum.co/the-capsized-e...
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
You may have a look at this:
http://code.tutsplus.com/tutorials/bu...
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
I already visited this page. This guy has done a full web app which is not like mine. All I need is to play an audio file, thats all. I dont need notification API, File API etc like no the page.

Tell me, you think it is practical for me to read 4 pages from that website just to know how to play a simple audio file? 80% of contents on that page is outside what I want?.

I tried these codes on the Phonegap documentation


<script>
function playAudio(url) {
var my_media = new Media(url,
function () {
console.log("playAudio():Audio Success");
},
function (err) {
console.log("playAudio():Audio Error: " + err);
}
);
my_media.play();
}
</script>



a href="#" onclick="playAudio('demo.mp3');">Play Audio</a>


Not playing at all!
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
OK. And now you want me to find out what's wrong in your app?

I would check:
1. was your config.xml found? was it parsed?
2. is the plugin properly activated?
3. does the Media constructor return a Media object?
4. what is in your console after creating the object?
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
You at least need the file = '/android_asset/www/' + file ; code from the code I sent originally.
(Edited)
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
Yes, the config/xml does not hve any issue and it is working well. The Media API is in the xml file, so, I guess it is activated. I dont have any error message when clicking the button toplay.

@John, can you elaborate more? Should I do it like this:

a href="#" onclick="playAudio('/android_asset/www/demo.mp3');">Play Audio

If I am not wrong, I do not have /android_asset/www/' but just the www folder as I am building on Phonegap cloud.
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
I also tried John's code:


<script>
function mediaSuccess() {
console.log( 'mediaSuccess' );
}
function mediaError( errObj ) {
console.error( 'mediaError code=' + errObj.code +
' message=' + errObj.message );
}
function mediaStatus() {
console.log( 'mediaStatus' );
}
function createMedia( file ) {
if ( typeof Media !== 'undefined' ) {
if ( (typeof device !== 'undefined') &&
(device.platform === 'Android') ) {
file = '/android_asset/www/' + file ;
}
return new Media( file, mediaSuccess,
mediaError, mediaStatus );
}
else {
return file ;
}
}
function playSound( media ) {
if ( appPaused ) {
return ;
}
if ( typeof Media !== 'undefined' ) {
media.seekTo(0);
media.play();
}
else {
console.log( 'playSound ' + media );
}
}
// preload sound files
snap_mp3 = createMedia( 'demo.mp3' );
// play sound file
playSound(demo.mp3 );
</script>



<a href="#" onclick="playSound();">Play Audio</a>


In vain!
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
snap_mp3 = createMedia( 'demo.mp3' );

playSound(demo.mp3 );


This is the wrong parameter for the playSound function.
[But my first guess is that your plugin isn't ready to go, even though you assume that it is.]
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
Can you tell me the correct parameter? Also, how to correct the plugin thing? It is the config.xml file.


<gap:plugin name="org.apache.cordova.media"/>


I spent nearly 9 hours to figure out how to play an audio on Phonegap. I hope I succeed. Also, I hope that Phonegap webview will accept the audio tag in HTML5... Imagine, many people who are creating games and so, they have to spend huge amount of time on javascript just to play a simple audio.

Hope things will change..
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
In the current version of Android's webview the <audio> tag does not work. So you have to use a plugin.

In the org.apache.cordova.media plugin, when playing sounds on an Android device, you need to prepend /android_asset/www/ to the filename.

My main advice for you is to figure out how to debug your app while it is running on an Android device. Here's a recent summary of available options - https://github.com/phonegap/phonegap/...

When your app doesn't work, you should try to determine what parts are working and what parts are not. Usually you can narrow it down to a specific line of javascript that is not doing what you think it should. If you post that line of code to this forum, someone will usually give you ideas on what could be wrong.
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
But I have checked everything, and I dont see any issue. There is no error in coding as well. I followed all your instructions well, but in vain. Does the plugin work on the latest phonegap vesion? im using the latest, 3.6.3
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
Yes, the plugin works with the 3.6.3 version of PhoneGap. I have tested it with a Samsung Galaxy S5.

Please be more specific about where the error occurs.
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
I do not see any error message or any error in the codes. I did what you toldme to do. I even posted the odes above.

If what I did in the codes above is OK, it should work. In addition, the plugin is in the config.xml file as I mentioned earlier. Must I put the cordova.js file as well?

Do you have an index.html sample page where I can look?
Photo of ali ja

ali ja

  • 57 Posts
  • 0 Reply Likes
If I send you a sample of my project, will you able to take a look? I will just send the html file, one mp3 and the config.xml file, thats all. Or,I can post all the codes here, including the config.xml file.
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
I do not see any error message

You don't even see any message. And that is bad, because both in the success callback and in the error callback, you are triggering a message. If neither success nor error callback function is called, then the whole object is probably undefined.

Have you:
- validated your config.xml?
- checked whether or not phonegap.js is referenced
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
You might add some console.log statements to determine what is working. Make sure you are able to see that output. I typically watch the logging by connecting my device to my computer with a USB cord and then use one of the following commands:

adb logcat

adb logcat -v time | find "chromium"

This conversation is no longer open for comments or replies.