Media Object in PhoneGap

Introduction

We can record and play audio files on a device using the Media object. It takes the four parameters:

src: It represents the URL that contains the audio content.
mediaSuccess: It is optional and invoked after the media onject has completed the current play/record and stop action.
mediaError: When the error has occured then this is invoked.
mediaStatus: It indicate the status changes.

Methods in Media

media.getCurrentPosition: Returns the current position within the audio file. It takes two parameters; the first is the mediaSuccess and the second is the mediaError. The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example

  // Audio player       

        var my_media = new Media(src, onSuccess, onError);

        // Update media position every second

        var mediaTimer = setInterval(function () {

            // get media position

            my_media.getCurrentPosition(

            // success callback

            function (position) {

                if (position > -1) {

                    console.log((position) + " sec");

                }

            },

            // error callback

            function (e) {

                console.log("Error getting pos=" + e);

            }

        );

        }, 1000);

media.getDuration: Returns the duration of the audio file. It is a synchronous function that returns the duration of the sudio file if the file is known if unknown then return -1.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

 

Example
 

// Audio player       

        var my_media = new Media(src, onSuccess, onError);

        // Get duration

        var counter = 0;

        var timerDur = setInterval(function () {

            counter = counter + 100;

            if (counter > 2000) {

                clearInterval(timerDur);

            }

            var dur = my_media.getDuration();

            if (dur > 0) {

                clearInterval(timerDur);

                document.getElementById('audio_duration').innerHTML = (dur) + " sec";

            }

        }, 100);

media.pause: It will pause the playing audio files. The function media.pause is a synchronous function that pauses any audio files that are playing.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example
 

   // Play audio       

        function playAudio(url) {

            // Play the audio file at url

            var my_media = new Media(url,

            // success callback

        function () {

            console.log("playAudio():Audio Success");

        },

            // error callback

        function (err) {

            console.log("playAudio():Audio Error: " + err);

        });

            // Play audio

            my_media.play();

            // Pause after 10 seconds

            setTimeout(function () {

                media.pause();

            }, 10000);

        }

media.play: Starts or resumes an audio file. It is a synchronous function.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).
 

Example
 

// Play audio    

        function playAudio(url) {

            // Play the audio file at url

            var my_media = new Media(url,

            // success callback

        function () {

            console.log("playAudio():Audio Success");

        },

            // error callback

        function (err) {

            console.log("playAudio():Audio Error: " + err);

        });

            // Play audio

            my_media.play();

        }


media.release: Releases the underlying operating system audio resources. It is a synchronous function. This is particularly important for Android applications. The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example

// Audio player      

        var my_media = new Media(src, onSuccess, onError);

        my_media.play();

        my_media.stop();

        my_media.release();

media.seekTo: Sets the current position within an audio file. It is an asynchronous function that updates the curtrent position of the audio file. It will take a parameter called milliseconds that defines the playback position within the audio in milliseconds.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example
 

// Audio player      

        var my_media = new Media(src, onSuccess, onError);

        my_media.play();

        // SeekTo to 10 seconds after 5 seconds

        setTimeout(function () {

            my_media.seekTo(10000);

        }, 5000);


media.startRecord: Records an audio file. It is a synchronous function.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example
 

// Record audio       

        function recordAudio() {

            var src = "myrecording.mp3";

            var mediaRec = new Media(src,

            // success callback

        function () {

            console.log("recordAudio():Audio Success");

        },

            // error callback

        function (err) {

            console.log("recordAudio():Audio Error: " + err.code);

        });

            // Record audio

            mediaRec.startRecord();

        }

media.stop: Stops the audio file; it is a synchronous function.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).

Example
 

// Play audio   

        function playAudio(url) {

            // Play the audio file at url

            var my_media = new Media(url,

            // success callback

        function () {

            console.log("playAudio():Audio Success");

        },

            // error callback

        function (err) {

            console.log("playAudio():Audio Error: " + err);

        });

            // Play audio

            my_media.play();

            // Pause after 10 seconds

            setTimeout(function () {

                my_media.stop();

            }, 10000);

        }

media.stopRecord:  Stops the recording of an audio file; it is a synchronous function.
The supported platforms are Android, BlackBerry WebWorks (OS 5.0 and higher), iOS and Windows Phone 7 (Mango).
 

Example
 

// Record audio   

        function recordAudio() {

            var src = "myrecording.mp3";

            var mediaRec = new Media(src,

            // success callback

        function () {

            console.log("recordAudio():Audio Success");

        },

            // error callback

        function (err) {

            console.log("recordAudio():Audio Error: " + err.code);

        });

            // Record audio

            mediaRec.startRecord();

            // Stop recording after 10 seconds

            setTimeout(function () {

                mediaRec.stopRecord();

            }, 10000);

        }

 

MediaError:  It is an object that is used to returned the mediaError callback function where the error has occurred. The properties are a code and a message.
 

function (error) {

            // Handle the error

        }

 

The full example of using the media is:
 

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

    <title>Cordova WP7</title>

    <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title"

        charset="utf-8" />

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

    <script type="text/javascript">

        // Wait for Cordova to load  

        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready

        function onDeviceReady() {

            playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");

        }

        // Audio player

        var my_media = null;

        var mediaTimer = null;

        // Play audio 

        function playAudio(src) {

            // Create Media object from src

            my_media = new Media(src, onSuccess, onError);

            // Play audio

            my_media.play();

            // 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>

</head>

<body>

    <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.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>

</body>

</html>

 

Summary: In this article I discussed the various methods of Media and how we can use it.