Previous Page Next Page

4.12. Sound

4.12.1. Play a Sound

4.12.1.1. Problem

You need to play a sound in your application.

4.12.1.2. Solution

Use the Sound API within AIR to play an MP3 file.

4.12.1.3. Discussion

AIR includes complete support for accessing Flash Player APIs from JavaScript. This includes the Sound class that can be used to play local or remote MP3 files.

Playing a sound is simple, and requires two main steps:

  1. Create a URLRequest instance that references the local or remote sound.

  2. Pass the URLRequest to the Sound instance, and play it.

Here is the relevant code snippet:

var soundPath =
  new air.URLRequest("app-resource:/sound.mp3");
var s = new air.Sound();
    s.load(soundPath);
    s.play();

First, we create a URLRequest that points to the location of the MP3 file we will play. In this case, we use an app-resource URI that references the sound.mp3 file contained in the application install directory. You can also use any valid URI, including both file and HTTP URIs:

var soundPath =
  new air.URLRequest("app:/sound.mp3");

We then create an instance of the Sound class, pass the reference to the MP3 path, and then call play:

var s = new air.Sound();
    s.load(soundPath);
    s.play();

Here is the complete example with a Play button:

<html>
<head>

    <script src="airaliases.js" />
    <script type="text/javascript">

        function playSound()
        {
            var soundPath =
             new air.URLRequest("app:/sound.mp3");
            var s = new air.Sound();
                s.load(soundPath);
                s.play();
        }
    </script>

</head>

<body>
    <input type="button" value="Play" onClick="playSound()">
</body>
</html>

At this point, you should have a solid understanding of Adobe AIR, how to build AIR applications, and how to work with AIR APIs. Make sure to check the resources listed in the Preface to learn more advanced Adobe AIR development techniques.

Previous Page Next Page