Playing a Sound Effect in Java

后端 未结 1 1742
说谎
说谎 2021-01-16 22:09

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();
<         


        
相关标签:
1条回答
  • 2021-01-16 22:46

    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!

    0 讨论(0)
提交回复
热议问题