Use PhoneGap Media API & jQuery Mobile UI Framework

This  Tutorial  shows how to use AppLaud and the PhoneGap Media API to play an audio file, and use jQuery Mobile for a simple UI using buttons and updated text display. It also shows two ways to access the audio file: as a url, and locally (from the device) using the project’s /assets folder.

Prerequisites

  • Installation of the latest MDS  AppLaud plugin, see Get Started

Prep

  • MDS AppLaud 1.2 or above
  • All code provided in complete files as attachments to this page: index.html and main.js
  • Review PhoneGap Documentation

 

1. Create a new project

Create a new project using the project creation wizard. In the first window select:

  • Use Built-in PhoneGap
  • Use Built-in jQuery Mobile
  • Project Contents: Create Project from Specified Source Directory
    • Use the attached index.html file
    • Download into empty directory and Browse to its Location
  • Select Next > to proceed to the next window of the Project Wizard

Example text for the 2nd page of the project creation wizard shown below.

 p11

Note: The above image is specific to SDK Tools 13 and lower. This image will be updated soon. Refer to the latest Getting Started Tutorial, Section 3A Android Project Config for SDK Tools 14+ for the latest tools. 

Note: For best device coverage, use Min SDK 7. After selecting the highest build target (API Level 13 in the example above), manually change Min SDK Version to 8.


2. Add Audio Control Buttons and Data to index.html using jQuery Mobile

Note: If the project was created using the steps above, the scripts will be inserted into index.html as shown below. As this app uses the PhoneGap APIs, the PhoneGap line must be included (remove commenting shown below to include javascript):

   <!-- <script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script> -->


The app uses jQuery Mobile to define a jQuery Mobile page (
data-role="page") and three buttons (data-role="button") to control the media player with Start, Pause and Stop actions. Two text spans with html id’s are added so the total media length and current position can be updated dynamically from javascript. A two-block grid was used to display the data as the spacing of text in a grid provides a nice separation. The content is given an id (id="content-manual"), which will be used in the next tutorial.

 

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=screen.width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Audio Player</title>
<!-- NOTE: The following 4 lines are inserted by the project wizard -->
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0.css" type="text/css">
<script type="text/javascript" src="jquery.mobile/jquery-1.6.4.min"></script>
<script type="text/javascript" src="jquery.mobile/jquery.mobile-1.0.js"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>
</head>
<body>
<div data-role=”page” data-theme=”a” id=”page-home”>

<div data-role=”header” data-nobackbtn=”true” data-theme=”e”>
<h1>Audio Player</h1>
</div> <!– /header –><div data-role=”content” id=”content-manual” data-theme=”a”><div data-role=”button” id=”playaudio” data-theme=”e”>Play</div>
<div data-role=”button” id=”pauseaudio” data-theme=”e”>Pause</div>
<div data-role=”button” id=”stopaudio” data-theme=”e”>Stop</div>

<div class=”ui-grid-a”>
<div class=”ui-block-a”> Current: <span id=”audio_position”>0 sec</span></div>
<div class=”ui-block-b”>Total: <span id=media_dur>0</span> sec</div>
</div><!– /grid-a –>

</div>  <!– /content-manual –>
</div>  <!– /page –>
</body>
</html>


For more information on the html markup used above, see the jQuery Mobile documentation.

At this point the app can be run on a device or AVD for a UI sanity check. None of the buttons will work as the javascript functionality has not been implemented yet. The app should appear as below.

 


3. Add the javascript functionality

Import the file main.js (see attached) into the project’s /assets/www directory, or copy its contents into a .js file of any name. The javascript code will provide initialization and the functions for the buttons created with jQuery Mobile html markup.

Add the following line to index.html immediately AFTER all the other javascript file inclusions (substituting your file name if not main.js):

 

    <script type="text/javascript" charset="utf-8" src="main.js"></script>

To review main.js, start at the bottom where the new style of jQuery Mobile page initialization (page: page-home) waits for the pageinit event before initializing the buttons’ functions. jQuery Mobile style of coding is used to easily implement the actions to take when a ‘tap’ event is delivered for one of the three buttons:

 

$('#page-home').live('pageinit',function(){    $("#playaudio").live('tap', function() {
        // Note: two ways to access media file: web and local file       
        var src = 'http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3';
       
        // local (on device): copy file to project's /assets folder:
        // var src = '/android_asset/spittinggames.m4a';
       
        playAudio(src);
    });    $("#pauseaudio").live('tap', function() {
        pauseAudio();
    });
   
    $("#stopaudio").live('tap', function() {
        stopAudio();
    });
});

The implementation of the three functions playAudiopauseAudio, and stopAudio, is heavily borrowed from the PhoneGap Documentation and will not be reviewed here. Note that it was edited for robustness (e.g. maintain a pause state).

To update the current position in the media as it progresses, we simply provide this callback for use in PhoneGap’s media.getCurrentPosition function and call it about every second.

function setAudioPosition(position) {
    $("#audio_position").html(position + " sec");
}

Similar code is used to provide the total media length in the html’s span, "media_dur".

4. Add an audio file or use a url to provide the media content

The last piece to provide is the audio file to play. As of this writing, the url in the code is a freely accessed mp3 (also borrowed from the PhoneGap Doc). If it is no longer available substitute your own mp3 or m4a url, or use your own file by including it with the steps below.

 

        // Note: two ways to access media file: web and local file       
        var src = 'http://www.gaana.com/song.mp3';
       
        // local (on device): copy file to project's /assets folder:
        // var src = '/android_asset/song.mp3';

To include an audio file in your project and have it loaded onto your device:

  • Copy an mp3 or m4a file into the project’s /assets directory
  • Edit the line var src = '/android_asset/song.mp3' to reference your file name

About the /assets Directory: By default an Android app project will load the entire contents of /assets onto the device. Files placed here are accessible using /android_asset/<filename>. Larger files result in a longer wait for the app to load and run.

 

About the Two Ways to Import or Copy Files into a Project:

  • From Eclipse, use File -> Import or <right-click-on-directory> -> Import, select General -> File System then locate the directory containing the files. Eclipse will automatically update the project meta-data when files are added to a project this way.
  • From outside Eclipse (i.e. command ‘cp’, drag/drop or copy/paste), the files will appear in the Project Explorer, but you must doFile -> Refresh or <right-click-on-project-name> -> Refresh to update the project meta-data manually.

5. Run the App and hear a Song!

Load the app and test the buttons to hear music! The total and current media lengths should update as shown below. The Current time will stop when paused. Both times reset to zero when stopped.

 

Click on this image to download the Full Source Code:

z

Happy Coding..!

Leave a comment