Playing a Sound Effect in Java

南楼画角 提交于 2019-12-01 14:04:45

You could use MediaPlayer to play the sound. Here is what I usually use for all my audio.

public class APP extends Activity {

//ADD THIS LINE AND IMPORT MediaPlayer
MediaPlayer btnClick;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ADD THIS LINE TO YOUR onCreate METHOD AFTER YOU SET THE CONTENT VIEW
btnClick = MediaPlayer.create(this, R.raw.button_click);
    }
}

This sets up your audio and what it should play. It will play your sound until it is finished. Then add this line to wherever you want the sound to play:

btnClick.start();

If you want it to loop (a soundtrack or song), add this:

btnClick.setLooping(true);

Once you are finished with the soundtrack that you looped or you are finished with the application, add this to stop the audio:

btnClick.stop();

OR

btnClick.release();

So technically you would be adding 2 lines for the MediaPlayer itself, 1 line to start it, and 1 line to end it (optional but best for good programming habits and practices).

I hope this thoroughly answers your question. Cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!