2013-04-06 77 views
0

我有一個佈局,其中多個按鈕的按鈕一個聲音播放respectively.My代碼showing.onclick就像但它不起作用: -如何在佈局中播放按鈕的聲音onclick?

@Override 
public void onClick(View view) { 
    resetPlayer(); 
    int index = 0; 
    if (view.equals(objbutton1)) 
     index = R.raw.sound1; 

    while (true) { 
     this.objplayer = MediaPlayer.create(this, index); 
     this.objplayer.setLooping(false); 
     this.objplayer.start(); 
     this.objplayer 
       .setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
        @Override 
        public void onCompletion(MediaPlayer mp) { 
         MainActivity.this.objplayer.release(); 
         MainActivity.this.objplayer = null; 

        } 
       } 
       ); 
     if(view.equals(objbutton2)) 
     { 
      index=R.raw.sound2; 
      continue; 

     } 
     if(view.equals(objbutton3)) 
     { 
      index=R.raw.sound3; 
      continue; 

     } 
     if(view.equals(objbutton4)) 
     { 
      index=R.raw.sound4; 
      continue; 

     } 
     if(view.equals(objbutton5)) 
     { 
      index=R.raw.sound5; 
      continue; 

     } 
     break; 
    } 

} 

private void resetPlayer() { 
    if (this.objplayer != null) { 
     if (this.objplayer.isPlaying()) 
      this.objplayer.stop(); 
     this.objplayer.release(); 
     this.objplayer = null; 
    } 

應用程序是隻打了一個聲音,當點擊另一個按鈕沒有健全的改變

+1

爲什麼你使用'while(true)'? – FoamyGuy 2013-04-06 14:52:32

+0

,因爲我想播放聲音直到完成,請給我建議 – SKT 2013-04-06 14:53:46

回答

0

使用此

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), index); 
        mp.start(); 

像...

private MediaPlayer mp; // declare it in public area. 

    public void onClick(View view) { 
    int index = 0; 
    if (view.equals(objbutton1)){ 
     index = R.raw.sound1; 
      if(mp !=null && mp.isPlaying()) mp.stop(); 
     mp = MediaPlayer.create(getApplicationContext(), index); 
      mp.start(); 
     } 
     if(view.equals(objbutton2)) 
     { 
      index=R.raw.sound2; 
      if(mp !=null && mp.isPlaying()) mp.stop(); 
     mp = MediaPlayer.create(getApplicationContext(), index); 
      mp.start(); 
     } 
     if(view.equals(objbutton3)) 
     { 
      index=R.raw.sound3; 
      if(mp !=null && mp.isPlaying()) mp.stop(); 
      mp = MediaPlayer.create(getApplicationContext(), index); 
     mp.start(); 
     } 
     if(view.equals(objbutton4)) 
     { 
      index=R.raw.sound4; 
      if(mp !=null && mp.isPlaying()) mp.stop(); 
      mp = MediaPlayer.create(getApplicationContext(), index); 
     mp.start(); 
     } 
     if(view.equals(objbutton5)) 
     { 
      index=R.raw.sound5 
      if(mp !=null && mp.isPlaying()) mp.stop(); 
     mp = MediaPlayer.create(getApplicationContext(), index); 
     mp.start(); 
     } 
} 

並在onDestroy()把這個mp.release();

+0

嗨這不適用於我我的要求是,假設我點擊第一個按鈕聲音開始,這裏有兩個例子,如果我沒有按任何其他按鈕,然後第一個聲音會直到完成其他情況下,如果我按其他按鈕然後首先釋放和其他聲音將播放。 – SKT 2013-04-06 15:23:43

+0

我編輯了我的答案。 – AwadKab 2013-04-06 16:38:47