Search code examples
javaandroidmp3alarm

Android Studio Alarm Clock MP3 Song


I'm making an alarm clock. I have the codes below. However, the notification music is working. I want it to play the mp3 file I set. What should I do?

@Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null)
        {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();
    }

Solution

  • Try this below code :

       Uri alarmUri  = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
       if (alarmUri == null)
        {
          MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
           mp.start();
        }
    

    Please used below code when you get notification in BroadcastReceiver then call activity in that activity class used below code so play sound file.

     mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
     mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
     mMediaPlayer.setLooping(true); 
     mMediaPlayer.start();