Android:如何播放Mp3声音作为通知?

时间:2016-12-13 11:35:10

标签: java android notifications

我有一个倒计时,当它完成后,它会调用以下onFinish方法:

public void onFinish() {
    azanCountdownH1.setText("Get ready now");
}

为了能够在倒计时结束时播放mp3文件,我将onFinish方法更改为:

public void onFinish() {
    playNotification();
    azanCountdownH1.setText("Get ready now");
}

playNotification看起来完全一样:

public static void playNotification(){
    MediaPlayer mp = MediaPlayer.create(MyApplicationContext.getAppContext(), R.raw.azan);
    mp.start();
}

但它不起作用!!

Android-Studio上的Android Moniter上显示以下内容:

enter image description here

有关错误的内容或位置的任何消息?!

3 个答案:

答案 0 :(得分:1)

传递给MediaPlayer.create()的Context null 。我建议将Context传递给你的playNotification方法:

public void onFinish() {
    playNotification(this);
    azanCountdownH1.setText("Get ready now");
}


public static void playNotification(Context context){
    MediaPlayer mp = MediaPlayer.create(context, R.raw.azan);
    mp.start();
}

答案 1 :(得分:1)

尝试使用此代码希望这可以帮助您..

public void onFinish() {
    azanCountdownH1.setText("Get ready now");
    playNotification(youractivity.this);
}

public void playNotification(Context context){
  MediaPlayer mp = new MediaPlayer();
  mp = MediaPlayer.create(context, R.raw.azan);
  mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  mp.start();
}

答案 2 :(得分:1)

您可能传递了错误的Context,因此只需将Activity.this改为Activity

public static void playNotification(){
    MediaPlayer mediaplayer = MediaPlayer.create(Activity.this, R.raw.azan);        
    if(mediaplayer == null) {            
        Log.v(TAG, "Create() on MediaPlayer failed.");       
    } else {
    mediaplayer.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mediaplayer) {
            mediaplayer.stop();
            mediaplayer.release();
        }
    });

    mediaplayer.start();
    }
}