QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Create a Music Player App using Intel XDK

Create a Music Player App using Intel XDK

intel-xdk-music-app

This post is a part 34 of Intel XDK Complete Tutorial post series.

In this tutorial we will look at Intel XDK’s Audio APIs. Most apps require sound to be played therefore exploring this API is very important. In this tutorial we will first learn how to include Intel XDK audio plugin in our app, then explore various audio apis and then we will finish the tutorial by creating a music player app.

Including Intel XDK Player Plugin

Before we start coding you need to make sure you have included Intel XDK player plugin which exposes all the sound APIs.

Screen Shot 2014-12-12 at 11.42.45 am

Audio File Format

You should always consider to play MP3 audio format because all devices support MP3. In case you are planning to play ACC or OGG then every device won’t be able to play.

Downloading an MP3 File and Putting it in WWW Directory

Before we start exposing this plugin we need to have a MP3 file in our application’s WWW directory for testing. You can either download a mp3 file manually and copy it or else download a MP3 file using JavaScript into the WWW directory.

For this tutorial I have a sound.mp3 file in sounds directory inside WWW directory.

Playing a MP3 File in Background

Here is the code to play an MP3 file which resides in WWW directory

        function playSound()
        {
            //Parameters:
            //1. File path relative to the WWW directory
            //2. Loop or not.
            intel.xdk.player.startAudio("sounds/sound.mp3", false);
        }
       
        document.addEventListener("intel.xdk.player.audio.start", function(){
            //started playing audio in background
        }, false);
       
        document.addEventListener("intel.xdk.player.audio.stop", function(){
            //Playing audio finished. Its also fired when intel.xdk.player.stopAudio() is called.
        }, false);

        document.addEventListener("intel.xdk.player.audio.busy", function(){
            //intel.xdk.player.startAudio is already playing an another audio file
        }, false);
       
        document.addEventListener("intel.xdk.player.audio.error", function(){
            //an error occured so audio cannot be played
        }, false);

If you want to stop the audio played by intel.xdk.player.startAudio, you can do this using this code

        function stopSound()
        {
            //stops audio if intel.xdk.player.startAudio is playing any. Then it fires the intel.xdk.player.audio.stop event.
            intel.xdk.player.stopAudio();
        }

While the MP3 file is playing you can seek using this code

// seek 30 seconds into the file and fires intel.xdk.player.audio.currenttime.set Event. If you pass 0 then it will seek to the beginning.
intel.xdk.player.setAudioCurrentTime(30);

document.addEventListener("intel.xdk.player.audio.currenttime.set", function(){
    //current position of the audio
    alert('Audio Current Time: ' + intel.xdk.player.audioInfo.currentTime);
}, false);

You can continuously watch the current position of the audio using this code

function watch() {
    alert('Audio Current Time: ' + intel.xdk.player.audioInfo.currentTime);
}
                       
// start a watch on the current audio track. Callback is fired every 1 second. Make sure u fire this function after intel.xdk.player.startAudio
var watchID = intel.xdk.player.watchAudioCurrentTime(watch, 1000);

You can also find the length of the audio

alert('Audio Current Track Length: ' + intel.xdk.player.audioInfo.duration);

intel.xdk.player.startAudio doesn’t provide any UI therefore you need to build your own music player UI so that user can control the playing of audio.

While playing a music using intel.xdk.player.startAudio if user locks the screen or changes app state to background then audio stops playing therefore intel.xdk.player.startAudio is not a good choice to create a music player app instead its a good choice if you want to play background music while app is running in foreground.

Playing MP3 using Default Music Player

Intel XDK does provide APIs to play music using device’s default music player. Here is the code to play a mp3 file using device’s default music player. Music player is launched inside the app and music is played.

        function playMusic()
        {
            //this function launches default mp3 player and plays the sound.mp3 music file.
            intel.xdk.player.playPodcast("http://labs.qnimate.com/sound.mp3");
        }
       
        document.addEventListener("intel.xdk.player.podcast.start", function(){
            //started playing music
            alert("start");
           
        }, false);
       
        document.addEventListener("intel.xdk.player.podcast.stop", function(){
            //music finished or player closed
            alert("stop");
        }, false);
       
        document.addEventListener("intel.xdk.player.podcast.error", function(){
            //error occured therefore music cannot be played
            alert("error");
        }, false);
       
        document.addEventListener("intel.xdk.player.podcast.busy", function(){
            //another music is already being played
            alert("busy");
        }, false);

The music file must be there is local or remote web server because intel.xdk.player.playPodcast takes a complete URL to a mp3 file for playing it. Some music apps allow users to download mp3 files, in that case you need to download the file into WWW directory and then provide the localhost URL to the file.

While playing a music using intel.xdk.player.playPodcast if user locks the screen or changes app state to background then also the music continues playing. This is what makes it a good choice for creating a music player app.

Here is the screenshot on how the player looks in the app
IMG_0553

In Android the above code continues playing music even if user presses home button and takes the app to background state. But in iOS the sound stops when user presses the home button. So if you are building a cordova hybrid app then you need to use Background Audio plugin for iOS.

Screen Shot 2014-12-31 at 5.40.34 pm

But when you are building a legacy app you can set background audio permission for playing audio in background.

This is how you set audio permission for iOSScreen Shot 2015-01-01 at 2.42.40 pm

This is how you set audio permission for Android Screen Shot 2015-01-01 at 2.43.58 pm

This method is great for creating a music player app. But the problem with this method is that it doesn’t allow player UI customization and also you need to pause the player to change track.

HTML5 Audio API

HTML5 audio api’s can also be used to play music but they aren’t a good choice for creating a music app. Because they stop playing when user locks the screen or changes app state to background. They are good as long as app is open.

Cordova Media Plugin

Many Intel XDK APPs use cordova media plugin to play music. Cordova Media APIs provide similar kinds of interface as intel.xdk.player.startAudio. Benefit of using cordova media plugin from intel.xdk.player.startAudio is that it continuous playing of music even if screen is locked. The default music player is displayed when screen is locked.

This plugin also lets you seek the audio manually. Therefore this plugin is considered the best way to build a music player app.

Here is an example code for playing music using Cordova Media Plugin.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <style>
        @-ms-viewport { width: 100vw ; zoom: 100% ; }                          
        @viewport { width: 100vw ; zoom: 100% ; }
        @-ms-viewport { user-zoom: fixed ; }                                    
        @viewport { user-zoom: fixed ; }
    </style>

    <script src="lib/ft/fastclick.js"></script>

    <link rel="stylesheet" href="css/app.css">
   
</head>
<body>
        <a href="#" class="btn large" onclick="playAudio('http://labs.qnimate.com/sound.mp3');">Play Audio</a>
        <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a>
        <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a>
        <p id="audio_position"></p>
    <script src="intelxdk.js"></script>        
    <script src="cordova.js"></script>          
    <script src="xhr.js"></script>              

    <script src="js/app.js"></script>
    <script src="js/init-app.js"></script>
    <script src="js/init-dev.js"></script>
    <script>
        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // device APIs are available
        //
        function onDeviceReady() {
            playAudio("http://labs.qnimate.com/sound.mp3");
        }

        // Audio player
        //
        var my_media = null;
        var mediaTimer = null;

        // Play audio
        //
        function playAudio(src) {
            if (my_media == null) {
                // Create Media object from src
                my_media = new Media(src, onSuccess, onError);
            } // else play current audio
            // Play audio. playAudioWhenScreenIsLocked make sure the audio is playing even if screen is locked.
            my_media.play({ playAudioWhenScreenIsLocked : true });

            // Update my_media position every second
            if (mediaTimer == null) {
                mediaTimer = setInterval(function() {
                    // get my_media position
                    my_media.getCurrentPosition(
                        // success callback
                        function(position) {
                            if (position > -1) {
                                setAudioPosition((position) + " sec");
                            }
                        },
                        // error callback
                        function(e) {
                            console.log("Error getting pos=" + e);
                            setAudioPosition("Error: " + e);
                        }
                    );
                }, 1000);
            }
        }

        // Pause audio
        //
        function pauseAudio() {
            if (my_media) {
                my_media.pause();
            }
        }

        // Stop audio
        //
        function stopAudio() {
            if (my_media) {
                my_media.stop();
            }
            clearInterval(mediaTimer);
            mediaTimer = null;
        }

        // onSuccess Callback
        //
        function onSuccess() {
            console.log("playAudio():Audio Success");
        }

        // onError Callback
        //
        function onError(error) {
            alert('code: '    + error.code    + '\n' +
                  'message: ' + error.message + '\n');
        }

        // Set audio position
        //
        function setAudioPosition(position) {
            document.getElementById('audio_position').innerHTML = position;
        }

    </script>
</body>
</html>

In Android the above code continues playing music even if user presses home button and takes the app to background state. But in iOS the sound stops when user presses the home button. So if you are building a cordova hybrid app then you need to use Background Audio plugin for iOS. But when you are building a legacy app you can set background audio permission for playing audio in background.

When screen is locked in iOS, the default music player is displayed. It can several controls next/previous buttons and also displays several information like song image, artist, album etc. You can control the music player when screen is locked using RemoteControls plugin.

Dec 12, 2014Narayan Prusty
Creating Full Screen Grid Layouts using jQuery NestedWordPress Enqueue Scripts/Styles only if Widget is Active
Comments: 11
  1. Clayton
    5 years ago

    Hi Guys, i am stuck in a project i made a game in construct 2, it has audio sounds that plays in the background as every game but i want the player to be able to play musics on his iphone while playing the game, because everytime i tried it with plugins if a music is playing and i open the app game the music stops, any kind of help is welcomed.
    Thanks

    ReplyCancel
  2. Elias
    5 years ago

    Hi, I would like to create an application to play streaming radio.
    you know what is the right way?

    ReplyCancel
  3. sandy
    6 years ago

    Please provide the code on git hub . it becomes easy to learn and read code .! just reading the post is insufficient to learn .

    Thanks
    sandeep

    ReplyCancel
  4. Paolo
    6 years ago

    Hi thanks for your support , but the code not run for begginers, its very dificult to run the samples, why you dont put a downloadable samples thats works , this way is easy to lear wit functional samples…. Thank you again

    ReplyCancel
  5. rajkumar
    7 years ago

    Hi,

    Iam trying to use html 5 video tag to play a video from my resource folder inside the app [www]; it was not at all playing. i frustrated, can you please help me out form this case.

    [Note: video has to play only from source folder in the app; not form the URL like http://]

    ReplyCancel
  6. BoltCrank
    7 years ago

    Hello Mr! awesome articles as always, but i have something to add!

    you said:

    “HTML5 audio api’s can also be used to play music but they aren’t a good choice for creating a music app. Because they stop playing when user locks the screen or changes app state to background. They are good as long as app is open.”

    well i’ve installed the background plugin and im using the next html5 api code:

    pretty basic, but it does work! the plugin handles this code properly and stays in background.

    i put this in case someone is facing a similar problem,

    (i didnt installed neither the media plugin or the player plugin, and it worked like a charm. )

    keep the good work!

    ReplyCancel
    • BoltCrank
      7 years ago
      ReplyCancel
    • Narayan Prusty
      7 years ago

      One issue using HTML5 audio is that when you lock the screen you won’t see the music controls.

      As there are a lot of plugins available you can do almost anything.

      ReplyCancel
  7. Neriton
    7 years ago

    Tentei todas as formas acima e nenhuma funcionou no meu moto g Android 5.0.1.

    Poderia me enviar um quickstart do intel.xdk.player.playPodcast já com os botões. Obrigado.

    I tried all of the above forms and no work on my bike g Android 5.0.1.

    Could you send me a quickstart intel.xdk.player.playPodcast already with the buttons. Thank U.

    ReplyCancel
  8. Pratiti
    7 years ago

    Hi,

    I used your code for playing audio in background. It worked fine.

    Next what I want to do is, I need to play audio for a predefined time, like for 10min, so what I did is, I used watchAudioCurrentTime method and using this 1 sec callback, I estimated 10min, after which I implemented the code to stop, which works perfectly fine on my Android 4.4.4 device, but running the same APK on Android 5.0.1 device, doesn’t stop audio, they audio keeps on playing even after 13 min.

    Any idea, what’s wrong?
    Or any better way to achieve this?

    ReplyCancel
    • Narayan Prusty
      7 years ago

      I would recommend you to debug the app by look at the JS console for error while executing the stop function.

      If you are running the apk for testing then debug using http://jsconsole.com/

      Thanks.

      ReplyCancel

Leave a Reply to Neriton Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

7 years ago 12 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Including Intel XDK Player Plugin
  • Audio File Format
  • Downloading an MP3 File and Putting it in WWW Directory
  • Playing a MP3 File in Background
  • Playing MP3 using Default Music Player
  • HTML5 Audio API
  • Cordova Media Plugin
Related Articles
  • Playing Videos in Intel XDK APP
  • Record Microphone Audio using Intel XDK
  • Downloading Files and Showing Progress using Intel XDK
  • Record Video using Intel XDK
  • Accessing User Phone Contacts using Intel XDK
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license