我有一个应用程序,其中AlertDialog在某种情况下弹出。我想在它显示的时候附上一个声音。我的活动名为NfcScannerActivity。
我正在尝试使用MediaPlayer播放声音,但它不会播放。该文件是meep2.mp3,位于thr Raw文件夹中。任何想法为什么不玩?
感谢。
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
NfcscannerActivity.this);
// set title
alertDialogBuilder.setTitle("Sign In Alert ");
// set dialog message
alertDialogBuilder
.setMessage("You have just signed out from this tag. ( " + tagUserName + " )" +
" Click OK to sign back in at this client or click CANCEL to decline the sign in")
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//do something
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
Log.e(TAG, "Cancelled the transaction as already signed out within last 2 mins on same tag");
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
try{
// show it
alertDialog.show();
MediaPlayer mediaPlayer = MediaPlayer.create(NfcscannerActivity.this, R.raw.meep2);
mediaPlayer.prepare();
mediaPlayer.start();
//mediaPlayer.release();
//mediaPlayer = null;
}catch(Exception e){
//ignore
}
[编辑]
final MediaPlayer mediaPlayer = MediaPlayer.create(NfcscannerActivity.this, R.raw.alert);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mediaPlayer.start();
答案 0 :(得分:2)
根据MediaPlayer.create(..)
的{{3}},您无需再致电mediaPlayer.prepare()
。
但是,您可以实施Documentation,可以使用MediaPlayer.onCompletionListener注册到MediaPlayer
。在此回调中,您应该使用MediaPlayer
释放mediaPlayer.release()
的资源。