简体   繁体   中英

Android: how to Play Mp3 sound as a notification?

I have a countdown that, when it is done, it invokes the following onFinish method:

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

In order to be able to play a mp3 file at the end of the countdown, I changed the onFinish method to:

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

Where playNotification looks exactly like:

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

But it is not working !!

On Android Moniter on Android-Studio it is showing the following:

在此处输入图片说明

Any suugestion on what or where the bug might be ?!

the Context you pass to MediaPlayer.create() is null . I would suggest to pass the Context to your playNotification method:

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();
}

Try to this code hope this can help you..

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();
}

You might be passing a wrong Context so just replace Activity.this with your Activity name

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM