How to play sounds in android

September 19, 2012 | Rishabh Agrawal | General

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, R.raw.click);//click sound is fetched from raw folder

public void onClick(View v)

{
// actions taken when Buttons are clicked
switch (v.getId())
{
case R.id.playBtn_id: // play click sound
mp.start();//Starts or resumes playback
//put your code here
break;

case R.id.stopBtn_id: // play click sound
mp.stop();//Stops a playback
//put your code here
break;

}
}

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.setAudioStreamType(AudioManager.STREAM_MUSIC);
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.


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal