Android – Playing sounds and running a code after finishing

Place all your sound files in .mp3 format in the \res\raw folder – use only small letters and no spaces in the names. Here are the sounds I have used for Flexi Dice, my custom dice roller:

Playing sounds

Use the following code to play the sound and run a procedure after finishing playing:

MediaPlayer mediaplayer = MediaPlayer.create(this, R.raw.name_of_sound_filename_without_extension); // e.g. R.raw.multiple_roll_1
long duration = mediaplayer.getDuration();
mediaplayer.start();

new Timer().schedule(new TimerTask() {
	@Override
	public void run() {
		runOnUiThread(new Runnable() {
			public void run() {
				// your code to be run after playing
			}
		});
	}
}, duration);

You wouldn’t want to play the sounds if the user was on an important meeting, would you? Use this code to check if the phone is in the silent mode:

AudioManager audio = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

switch (audio.getRingerMode()) {
	case AudioManager.RINGER_MODE_SILENT:
	case AudioManager.RINGER_MODE_VIBRATE:
		// Do not play sounds
		break;
	default:
		// Play sounds
		break;
}

←Table of contents
←My apps, games and other projects

Advertisements
Android – Playing sounds and running a code after finishing

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s