2017-01-18 19 views
1

私は以下のルールでデフォルトのサウンドを再生し、停止したい:Androidでデフォルトサウンドを自動的に再生/停止する方法は?

  1. 音が再生されない場合は、10秒でそれを再生してみましょう。
  2. サウンドが再生されている場合は、停止して最初の位置で再生します。

次のようにこれらの上記の規則に基づいて、私は機能をデザイン:

public MediaPlayer mp =null; 
public void playDefaultSound(){ 
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); 
    mp = MediaPlayer.create(getApplicationContext(), notification); 
    try { 
     if (mp.isPlaying()) { 
     mp.stop(); 
     mp.release(); 
     mp = MediaPlayer.create(getApplicationContext(), notification); 
     } 
     mp.start(); 
     Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
     public void run() { 
      mp.stop(); 
      mp.release(); 
      } 
     }, 10000); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
} 

をしかし、いつか、私はまだ2つのサウンドを聞く)最初のサウンド再生の場合には(演奏と私はplayDefaultSound(コールされています再び機能する)。 mp = MediaPlayer.create(getApplicationContext(), notification);mp.release()を削除するのが正しいと思いますか?これらのルールを満たすために関数を修正するにはどうすればよいですか?ありがとうございました

答えて

1
final MediaPlayer mp = new MediaPlayer(); 
public void playDefaultSound(){ 
     Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); 
     try { 
      if (mp != null && mp.isPlaying()) { 
       mp.seekTo(0); 
      } else { 
       mp.reset(); 
       mp.setDataSource(getApplicationNotification(), notification); 
       mp.start(); 
       Handler handler = new Handler(); 
       handler.postDelayed(new Runnable() { 
        public void run() { 
         mp.stop(); 
         mp.release(); 
        } 
       }, 10000); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
P.S. - Always see the state diagram or lifecycle of things whenever stuck. 

Ref : [Android Media Player State Diagram][1] 


    [1]: https://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram "MediaPlayer State Diagram" 
+0

ありがとうございます。しかし変数mpをチェックしてください。それは最終的な変数なので、elseステートでは代入できません。さらに、mp.seekTo(0)は、3行目でmp = nullを指定しているので、常に表示されます。 – user8264

+0

チェックしたところ、うまく機能しませんでした – user8264

+0

が編集されました。今すぐチェックしてください –

関連する問題