Monday, January 28, 2019
This is a very useful piece of code, playing simple sound effect on your app.
first open, res/raw/ and save your sound file inside the raw folder.
next you need to import the media class in your MainActivity.
import android.media.MediaPlayer;
now you can load your sound effect into your activity.
car_alarm = MediaPlayer.create(this, R.raw.car_alarm);
you may set loop, to have your effect play end to end.
car_alarm.setLooping(true);
finally you can have your sound played by the media class.
car_alarm.isPlaying();
use stop and then release once you no longer need it.
car_alarm.stop();
car_alarm.release();
It is said to be good practice to destroy your object, for memory reasons, this is how you do so.
@Overrideprotected void onDestroy() { // stop the sounds if(car_alarm.isPlaying()) car_alarm.stop(); car_alarm.release(); super.onDestroy(); }
place above code inside your MainActivity class.