Pin Me

How to Play Audio Files in the Google Android Programming Environment

written by: hardiks•edited by: Simon Hill•updated: 7/5/2011

This tutorial will show you how to play audio files in your newly created Android applications. This can be particularly useful when creating games.

  • slide 1 of 1

    Audio Playback in Android

    In this tutorial, I will show you how to play audio files in your Android application. Sounds can play a very important role in enhancing the usability of your application, they are especially useful if you are creating an interactive game. You might want to add various sound effects to your application or game which are played or executed when certain events occur.

    The Android development platform offers a set of built in classes which have defined functions to let you play multimedia content easily using the intents and activities mechanism.

    You can use the MediaPlayer class to play audio or video files from within your application. You can also play audio files stored in the device file system, embedded in the application or from a streaming source over the Internet. By default, Android supports file formats like WAV, OGG, MP3, M4A, OTA and AMR. Additionally, different devices may support more formats.

    To play any audio file in your application, you need to create an instance of the MediaPlayer class and then use methods like start(), stop() and pause() to control playback.

    First of all, create a new instance of MediaPlayer,

    MediaPlayer MPX = new MediaPlayer();

    Next, set the audio file to be played as the data source of the MediaPlayer instance.

    MPX.setDataSource("File Path");

    It is now in the Initialized state. Prepare the MediaPlayer instance for playback by


    This makes it transition to the Prepared state.

    Now you can use the following to control playback:


    Here is the complete example:

    MediaPlayer MPX = new MediaPlayer();

    MPX.setDataSource("File Path\File Name");





    You will need to enclose the whole code in an exception handling block as the file may / may not exist and the MediaPlayer instance could be null. This could cause the IllegalArgumentException and IOException to arise.