2012-09-03 17 views
0

我做了一個activity有一個音頻作爲背景音樂。當我添加一個跳過按鈕移動到另一個activity我的第一個活動的背景音樂不斷播放。這是我的代碼,請檢查併發布我應該添加到我的代碼中的內容。提前致謝!音頻連續播放,即使它移動到下一個活動

public class pgone extends Activity { 
    protected boolean _active = true; 
    protected int _splashTime = 7000; 
    public void onAttachedToWindow() { 
      super.onAttachedToWindow(); 
      Window window = getWindow(); 
      window.setFormat(PixelFormat.RGBA_8888); 


     } 

    MediaPlayer audio; 
    MediaPlayer SLONE; 

    private long splashDelay = 6000; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.pgone); 

     TimerTask task = new TimerTask() 
     { 

      public void run() { 

       Intent mainIntent = new Intent().setClass(pgone.this, pgtwo.class); 
       startActivity(mainIntent); 
       finish(); 

      } 

     }; 

     final Timer timer = new Timer(); 
     timer.schedule(task, splashDelay); 


     audio = MediaPlayer.create(this,R.raw.storyaud); 
     audio.start(); 

     SLONE = MediaPlayer.create(this,R.raw.sl1); 
     SLONE.start(); 


     final MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonbeep); 
     final Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 


Button skipButton = (Button)findViewById(R.id.skip); 
skipButton.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     Intent skipIntent = new Intent(pgone.this,choose.class); 
     startActivity(skipIntent); 
     mp.start(); 
     mVibrator.vibrate(500); 
     finish(); 
     timer.cancel(); 
     timer.purge(); 


    } 
}); 

    } 

    protected void exitByBackKey() { 

     AlertDialog alertbox = new AlertDialog.Builder(this) 
     .setMessage("Do you want to exit the game?") 
     .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 


      public void onClick(DialogInterface arg0, int arg1) { 

       finish(); 
      } 
     }) 
     .setNegativeButton("No", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface arg0, int arg1) { 
      } 
     }) 
      .show(); 
    } 

} 

回答

1

您應該在轉移到下一個活動之前停止音頻。嘗試通過mp.stop更換mp.start()()這裏,

Button skipButton = (Button)findViewById(R.id.skip); 
skipButton.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     Intent skipIntent = new Intent(pgone.this,choose.class); 
     startActivity(skipIntent); 
     mp.stop(); 
     mVibrator.vibrate(500); 
     finish(); 
     timer.cancel(); 
     timer.purge(); 


    } 
}); 
+0

謝謝!它有助於。 –

0

最簡單,最有效的方法 -

@Override 
    protected void onPause() { 
     super.onPause(); 
     yoursMusicPlayerObject.release(); 

    } 

開拓活動生命週期的的onPause階段,當你跳轉到下一個活動。剛釋放下使用I/O資源這是您的MediaPlayer對象。

+1

@ FrankN.Stein我編輯它。沒有任何藉口,只是我正在打字時走路。對於stackoverflow和android都是新的。謝謝 –