Media in PhoneGap

What Are Media Files?

The Media API lets you record and play back audio on a device. You can typically play audio files loaded locally on the device, or play audio files retrieved from the Internet.

Note: The current implementation does not adhere to a W3C specification for media capture, and is provided for convenience only. A future implementation will adhere to the latest W3C specification and may deprecate the current APIs.

var media = new media(src,mediaSuccess,[mediaError],[mediaStatus]);

The Media Object

The PhoneGap Media Object has following four parameters, three of which are optional:

src: A URL containing the audio content. (DOMString)
mediaSuccess: (Optional) The callback that is invoked after a Media object has completed the current play/record or stop action. (Function)
mediaError: (Optional) The callback that is invoked if there was an error. (Function)
mediaStatus: (Optional) The callback that is invoked to indicate status changes. (Function)

Using Media Methods

In this section, you learn how to use the main methods of the Media API. The methods allow you to play, record, and pause, among other things.

Note: If you're working with Version 0.9.4 or earlier on PhoneGap, you must ensure that all your callback functions are global in scope.

media.getCurrentPosition

To get the current position within an audio file, use media.getCurrentPosition, as shown here:

media.getCurrentPosition(mediaSuccess,[mediaError]);

The mediaSuccess function is a callback that is called with the current position, and the optional mediaError is a callback that's called in case of an error. The getCurrentPosition() method is an asynchronous function that returns the current position of the underlying audio file of a Media object.

Code:

var audio_file = new Media(src, onSuccess, onError);
var mediaTimer = setInterval(function ()
{
  
   audio_file.getCurrentPosition(function (position)
     {
         if (position > -1)
         {
              console.log((position/1000) + " sec");
         }
     },
  
   function (e)
     {
         console.log("Error getting pos=" + e);
     });
}, 2000);

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

getDuration

It actually returns the duration of an file.

media.getDuratiion()

getDuration() is a synchronous function that returns the duration (in milliseconds) of an audio file. To convert to seconds, you will need to divide by 1,000. If the duration is unknown, a value of -1 is returned. The following is sample code:

Code:

var
 audio_file = new Media(src, onSuccess, onError);
var
count = 0;
var
mytimerDur = setInterval(function () {
   count = count + 200;
   if
(count > 2000)
   {
       clearInterval(mytimerDur);
   }
   var
dur =  audio_file.getDuration();
   if
(dur > 0)
   {
      clearInterval(mytimerDur);
      document.getElementById('audio_duration').innerHTML = (dur/1000) + " sec";
   }
}, 200);

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.play

To start or resume playing an audio file, use the media.play() function, as shown in the following example:

media.play();

To actually play a file, you must pass in a URL, or a path to a locally stored file, as shown here:

Code:

function playAudio(url)
{
    var  audio_file = new Media(url, onSuccess, onError);
    function()
    {
       console.log("playAudio():Audio Success");
    }
    function(err)
    {
       console.log("playAudio():Audio Error: "+err);
    }
    audio_file.play();
}

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.pause

To pause the playing of an audio file, use the pause() method, as shown here:

media.pause();

Function media.pause() is a synchronous function that pauses playing an audio file. The following is sample code:

Code:

function playAudio(url)
{
    var  audio_file= new Media(url,
    function()
    {
        console.log("playAudio():Audio Success");
    },
 
   function(err)
    {
        console.log("playAudio():Audio Error: "+err);
    });
 
   audio_file.play();
 
   setTimeout(function() {
       audio_file();
     }, 5000);        
}

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.release

To releases the underlying operating systems audio resources, use release() method as shown here:

media.release();

Function media.release()  is a synchronous function that releases the underlying operating systems audio resources. This is particularly important for Androids because there is a finite number of OpenCore instances for media playback. The OpenCore libraries support media playback for audio, video, and image formats. You should always call this release function when you no longer need a media resource. The following is sample code:

Code:

var  audio_file= new Media(src, onSuccess, onError);
audio_file.play();
audio_file.stop();
audio_file.release();

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.startRecord

To start recording, use the startRecord() method, as shown here:

media.startRecord();

Function media.startRecord() is a synchronous function that starts recording an audio file. The following is sample code:

Code:

function recordAudio()
{
    var src = "myrecording.mp3";
    var  audio_file = new Media(src,onSuccess, onError);
 
   function()
    {
       console.log("recordAudio():Audio Success");
    }
 
   function(err)
    {
       console.log("recordAudio():Audio Error: "+ err.code);
    }
 
   audio_file.startRecord();
}

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.stopRecord

To stop recording a file, use the stopRecord() method, as shown here:

media.stopRecord();

Function media.stopRecord() is a synchronous function that stops recording an audio file. The following is sample code:

Code:

function recordAudio()
{
    var src = "myrecording.mp3";
    var  audio_file = new Media(src, onSuccess, onError);
    function()
    {
        console.log("recordAudio():Audio Success");
    },
    function(err)
    {
       console.log("recordAudio():Audio Error: "+ err.code);
    });
    audio_file.startRecord();
    setTimeout(function()
    {
        audio_file.stopRecord();
    }, 5000);
}

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

media.stop

To stop the playing of an audio file, use the stop() method, as shown here:

media.stop();

Function media.stop() is a synchronous function that stops playing an audio file. The following is sample code:

Code:

function playAudio(url)
{
    var audio_file = new Media(url,
 
   function ()
    {
       console.log("playAudio():Audio Success");
    },
 
   function (err)
    {
       console.log("playAudio():Audio Error: " + err);
    });
 
   audio_file.play();
 
   setTimeout(function ()
    {
         audio_file.stop();
    }, 5000);
}

Supported Platform

  • Android
  • iOS
  • Windows Phone 7 ( Mango )  

Handling Errors

The MediaError object is returned whenever you use the mediaError callback function. It contains two parts:

Code: This is one of the Predefined codes
Message: This is an error message that describes the details of the error.

The predefined error codes are constant.

  • MediaError.MEDIA_ERR_ABORTED
  • MediaError..MEDIA_ERR_NETWORK
  • MediaError.MEDIA_ERR_DECODE
  • MediaError.MEDIA_ERR_NONE_SUPPORTED

A more user-friendly approach would be to set up an array of error states that use the constants as keys, and your own friendlier error statement as the value. That way, you could display the friendlier message to the user. The following is an example:

function onError(myerror)
{
     var errors = {};
     errors[MediaError.MEDIA_ERR_ABORTED]= "Stop playing!";
     errors[MediaError.MEDIA_ERR_NETWORK]= "error in network!";
     errors[MediaError.MEDIA_ERR_DECODE] = "Could not decode file!";
     errors[MediaError.MEDIA_ERR_NONE_SUPPORTED] = "Format not supported!";
     alert("Media error: " + error[myerror]);
}

Here are some other useful resources which may help you

Working With JavaScript, CSS And HTML in PhoneGap
How to Get Device Information Using PhoneGap
How to find Longitude & Latitude of Geolocation in PhoneGap
Working with Accelerometer in PhoneGap
Events in PhoneGap

Up Next
    Ebook Download
    View all
    Learn
    View all