Playing a Sound Effect in Java

元气小坏坏 提交于 2019-12-01 12:53:21

问题


I'm trying to do the equivalent of this line of code, except substituting a small mp3 file for the system beep:

Toolkit.getDefaultToolkit().beep();

I have an mp3 file that has a little sound effect that I want to play. Is this a relatively easy thing to do? Can somebody show me the code to do this?


回答1:


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!



来源:https://stackoverflow.com/questions/11093157/playing-a-sound-effect-in-java

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