0

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();
    }
Uğur KILCI
  • 55
  • 1
  • 8

1 Answers1

0

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();
haresh
  • 1,424
  • 2
  • 12
  • 18
  • Where do I write "song.mp3"? My goal is to play song.mp3 on alarm. – Uğur KILCI Feb 01 '20 at 05:27
  • @haresh mb you provide the answer, but simply saying `try X` isn't helpful for others. What's more, your answer uses the `notification` variable, which is not described in the context of question. How should I define that variable/parameter, cause now it gives the syntax error. – itwasntme Feb 01 '20 at 05:34
  • @itwasntme sorry but i am not getting you? – haresh Feb 01 '20 at 05:36
  • I mean, using the variables (also their names) that wasn't used in question makes it difficult to reuse by others. So calling the `MediaPlayer.create(.....)` with `notification` is hard to determinate by others, same goes to `R.raw.sound1` - it's not shown/used anywhere else, I know I'd need to declare/put it in resources, but for some1 unfaimilliar it forwards to another problem. – itwasntme Feb 01 '20 at 05:48
  • I not understand ``` @Override public void onReceive(Context context, Intent intent) { Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (alarmUri == null) { MediaPlayer mp = MediaPlayer.create(context.getApplicationContext(), notification); mp.start(); } MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.sound1); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setLooping(true); mMediaPlayer.start(); } ``` – Uğur KILCI Feb 01 '20 at 23:24
  • is my answer was helpful then please upvote and accept and if you are still stuck please let me know – haresh Feb 02 '20 at 04:47