首页 > 代码库 > Android 播放声音

Android 播放声音

在Android应用中,有时候为了用户体验更佳,我们会为默写情况添加声音效果,比如点击按钮后发出声音,以下代码可以轻松实现声音效果:

new Thread(new Runnable() {
   @Override
   public void run() {
    // TODO Auto-generated method stub
    MediaPlayer mPlayer = MediaPlayer.create(
      getApplicationContext(), R.raw.switch_sound);
    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
     @Override
     public void onCompletion(MediaPlayer mp) {
      mp.release();
     }
    });
    try {
     mPlayer.prepare();
    } catch (IllegalStateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    mPlayer.start();
   }
  }).start();
 }