2012-04-01 34 views
16

Làm cách nào để tôi sử dụng trình nghe OnCompletion cho một số bản nhạc? Tôi muốn nhấn một nút để chuyển đến một hoạt động khác phát một số bản nhạc và sau đó quay lại khi quá trình phát nhạc kết thúc. Tôi allready mã hóa những thứ khác. Tôi chỉ không thể tìm ra cách sử dụng trình nghe OnCompletion?Trình nghe nhạc OnCompletion với MediaPlayer

Trả lời

32

Bạn nên đặt mã mà nên được chạy khi âm nhạc được hoàn thành trong OnCompletionListener, ví dụ:

mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    public void onCompletion(MediaPlayer mp) { 
     finish(); // finish current activity 
    } 
}); 
+0

Giải pháp hoàn hảo, đã làm việc cho tôi – Pitto

+0

Cảm ơn bạn rất nhiều !!! Nó đã làm việc :) –

6
mPlayer.setOnErrorListener(new OnErrorListener() { 
public boolean onError(MediaPlayer paramMediaPlayer, int paramInt1,int paramInt2) { 
// TODO Auto-generated method stub 
//your code if any error occurs while playing even you can show an alert to user 
return true; 
} 
}); 
mPlayer.setOnCompletionListener(new OnCompletionListener() { 
public void onCompletion(MediaPlayer mp) { 
// TODO Auto-generated method stub 
//your code if the file was completely played either show an alert to user or start another activity or file. 
//even you can finish you activity here 
}     
}); 
4

Tôi thấy rằng ở trên là đúng tuy nhiên tôi đã gặp khó khăn về nơi để đặt mã. Xem bên dưới, tôi đặt mã này sau mã của tôi để bắt đầu giai điệu!

playButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    mediaPlayer.start();  //Next line is the beginning of where to place the code. 
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mediaPlayer) { 
     Toast.makeText(MainActivity.this, "I'm Finished", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    } 
}); 
Các vấn đề liên quan