# Playing Sound and Music

In Monaca, there are two ways to play sound and music such as:

* [Using HTML5 \<audio> Tag](/sampleapp/tips/media.md#using-html5-lt-audio-gt-tag) (May not Work on iOS Devices)
* [Using Cordova Media Plugin](/sampleapp/tips/media.md#using-cordova-media-plugin) (Highly Recommended)

## Using HTML5 \<audio> Tag

{% hint style="info" %}
The HTML5 `audio` tag may not work properly on iOS devices.
{% endhint %}

### Playing Sound from External Sources

HTML5 `<audio>` tag can be used to play sound located on external sources by specifying its URL. For example, the following code snippet is using `<audio>` tag to play an audio file based on a specified source:

```markup
...
<body>
  <!-- Play the music when the Play control is pressed -->
  <audio src="External audio URL" controls></audio>
  <!-- The music is played as soon as the application is loaded -->
  <!-- <audio src="External audio URL" autoplay></audio> -->
</body>
...
```

### Playing the Sound Located inside a Monaca Project

HTML5 `<audio>` tag can also be used to play sound located locally within a Monaca project. For example, the following code snippet is using `<audio>` tag to play an audio file located under `www/` folder:

```markup
...
<body>
  <!-- Play the music when the Play control is pressed -->
  <audio src="sample.mp3" controls></audio>
  <!-- The music is played as soon as the application is loaded -->
  <!-- <audio src="sample.mp3" autoplay></audio> -->
</body>
...
```

![](/files/-Mfb1NRVSgjUQf4GeaGT)

## Using Cordova Media Plugin

With Cordova Media plugin, you have more functions to control over how you play a sound file such as start, pause, stop, resume, set volume and so on.

{% hint style="info" %}
Before getting started, you are required to [enable](/products_guide/monaca_ide/dependencies/cordova_plugin.md#import-cordova-plugins) Media plugin in Monaca Cloud IDE.
{% endhint %}

### Playing Sound from External Sources

In the following example, we will show you how use a sound file from an external source. You can play, pause and stop the music.

```markup
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
    <script src="components/loader.js"></script>
    <link rel="stylesheet" href="components/loader.css">
    <link rel="stylesheet" href="css/style.css">
    <script>
        var media = null;
        var mediaTimer = null;
        var srcFile = "External audio URL";

        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
            console.log("ready");
            media = new Media (srcFile , onSuccess, onError);
        }

        function playSound(){
            // play the media file one time.
            media.play({numberOfLoops: 0});
            // start the timer
            if (mediaTimer == null) {
                mediaTimer = setInterval(function() {
                    // Return a current playback position
                    media.getCurrentPosition(
                        //A Callback function if it's success
                        function(position) {
                            if (position > -1) {
                                //If the playback stops at "-0.001" position, set the timer to 0.
                                if(position == -0.001){
                                    position = 0;
                                }
                                setAudioPosition((position) + " sec");
                            }
                        },
                        //A callback function in case of failure
                        function(error) {
                            console.log("Error getting pos=" + error);
                            setAudioPosition("Error: " + error);
                        }
                    );
                }, 1000);
            }
        }

        function pauseSound(){
            if (media) {
                media.pause();
            }
        }

        function stopSound(){
            if (media) {
                media.stop();
            }
        }

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

        function onSuccess(){
            console.log("Successfully initialize a media file.");
        }

        function onError(error){
            console.log("Failed to initialize a media file. [ Error code: " + error.code + ", Error message: " + error.message + "]");
        }
    </script>
</head>
<body style="text-align: center">
    <h1>Playing Sound</h1>
    <button onclick="playSound()">Play</button>
    <button onclick="pauseSound()">Pause</button>
    <button onclick="stopSound()">Stop</button><br />
    <p id="audio_position"></p>
</body>
</html>
```

### Playing the Sound Located inside a Monaca Project

In the following example, we will show you how use a local sound file located under `www/` folder. You can play, pause and stop the music.

```markup
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
    <script src="components/loader.js"></script>
    <link rel="stylesheet" href="components/loader.css">
    <link rel="stylesheet" href="css/style.css">
    <script>
        var media = null;
        var mediaTimer = null;
        var srcFile = "sample.mp3";

        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
            console.log("ready");
            media = new Media (getPath() + srcFile , onSuccess, onError);
        }

        function getPath() {
            var str = location.pathname;
            var i = str.lastIndexOf('/');
            return str.substring(0,i+1);
        }

        function playSound(){
            // play the media file one time.
            media.play({numberOfLoops: 0});
            // start the timer
            if (mediaTimer == null) {
                mediaTimer = setInterval(function() {
                    // Return a current playback position
                    media.getCurrentPosition(
                        //A Callback function if it's success
                        function(position) {
                            if (position > -1) {
                                //If the playback stops at "-0.001" position, set the timer to 0.
                                if(position == -0.001){
                                    position = 0;
                                }
                                setAudioPosition((position) + " sec");
                            }
                        },
                        //A callback function in case of failure
                        function(error) {
                            console.log("Error getting pos=" + error);
                            setAudioPosition("Error: " + error);
                        }
                    );
                }, 1000);
            }
        }

        function pauseSound(){
            if (media) {
                media.pause();
            }
        }

        function stopSound(){
            if (media) {
                media.stop();
            }
        }

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

        function onSuccess(){
            console.log("Successfully initialize a media file.");
        }

        function onError(error){
            console.log("Failed to initialize a media file. [ Error code: " + error.code + ", Error message: " + error.message + "]");
        }
    </script>
</head>
<body style="text-align: center">
    <h1>Playing Sound</h1>
    <button onclick="playSound()">Play</button>
    <button onclick="pauseSound()">Pause</button>
    <button onclick="stopSound()">Stop</button><br />
    <p id="audio_position"></p>
</body>
</html>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://en.docs.monaca.io/sampleapp/tips/media.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
