How to play sounds in android

We can add sounds on various events like on item click ,button click etc. For playing sounds we use MediaPlayer object.
MediaPlayer class can be used to control playback of audio/video files and streams in the application.

1.For local resource.
Firstly to store the sound file we create a sub folder raw in the res folder. Then put your sound file in the raw folder.

The following code depicts how click sound is played when button is pressed. In this code sound is played on button click and stopped on another button click.

MediaPlayer mp;

mp = MediaPlayer.create(this,;//click sound is fetched from raw folder

public void onClick(View v)

{// actions taken when Buttons are clicked

switch (v.getId()) {

case // play click sound

mp.start();//Starts or resumes playback

//put your code here


case // play click sound

mp.stop();//Stops a playback

//put your code here




Similarly we can add sound in app anywhere we wish. We can explicitly start and stop a sound using mp.start() and mp.stop() .If we explicitly do not stop a sound file than it play till its completion.

2.Playing from a remote URL via HTTP streaming

This code shows you how you play audio from remote url :

String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
//setting audio stream type
mediaPlayer.setDataSource(url);//setting url as data source
mediaPlayer.prepare(); // for buffering
mediaPlayer.start();//starts playing

Hence, these are the two ways of playing sound using local and remote resources.


2 thoughts on “How to play sounds in android

  1. Your style is so unique compared to other folks I’ve read stuff from. Thanks for posting when you’ve
    got the opportunity, Guess I will just bookmark this web site.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s