Advertisement
Tech

Setting Audio Files to Play When Programming in the Google Android Programming Environment

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

By hardiks
Desk Tech
Reading time 2 min read
Word count 305
Google android Mobile Android sdk
Setting Audio Files to Play When Programming in the Google Android Programming Environment
Advertisement
Quick Take

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

On this page

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.

Advertisement

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.

Advertisement

First of all, create a new instance of MediaPlayer,

MediaPlayer MPX = new MediaPlayer();

Advertisement

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

MPX.setDataSource(“File Path”);

Advertisement

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

MPX.prepare();

Advertisement

This makes it transition to the Prepared state.

Now you can use the following to control playback:

Advertisement

MPX.start();MPX.pause();MPX.stop();

Here is the complete example:

Advertisement

MediaPlayer MPX = new MediaPlayer();

MPX.setDataSource(“File Path\File Name”);

Advertisement

MPX.prepare();

MPX.start();

Advertisement

MPX.pause();

MPX.stop();

Advertisement

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.

Keep Exploring

More from Tech

Filed under
Google android Mobile
More topics
Android sdk
Advertisement