How to play ringtone/alarm sound in Android
Asked Answered
S

13

138

I have been looking everywhere how to play a ringtone/alarm sound in Android.

I press a button and I want to play a ringtone/alarm sound. I could not find an easy, straightforward sample. Yes, I already looked at Alarm clock source code... but it is not straightforward and I cannot compile it.

I cannot make this work:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
    player.setAudioStreamType(AudioManager.STREAM_ALARM);
    player.setLooping(true);
    player.prepare();
    player.start();
}

I get this error:

04-11 17:15:27.638: ERROR/MediaPlayerService(30): Couldn't open fd for
content://settings/system/ringtone

So.. please if somebody knows how to play a default ringtone/alarm let me know.

I prefer not to upload any file. Just play a default ringtone.

Skidproof answered 11/4, 2010 at 18:28 Comment(0)
G
212

You can simply play a setted ringtone with this:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Glinys answered 19/12, 2011 at 22:17 Comment(10)
I still get an error - Failed to open ringtone content://settings/system/alarm_alertGuipure
Nice and simple. However, depending on the device, this method may interrupt other sounds (like music) that might be playing in Android.Heterography
Using getApplicationContext() might not be a very good option. More info here: #9123127Holophytic
@BartSimpson how u resolved issue i m also getting this errorCannular
I tried this but the sound may get cut off. I used MediaPlayer as igordcard@ answered it worked perfectly.Chabazite
Ringtone doesn't routed to bluetooth headset :(Enthronement
Ringtone can not stoppable. If start ringtone again, plays double. stopPrevious not working, by the way I create ringtone player with the same context object, not getapplicationcontext.Christiansand
may be change context or get system service for ringtonePhotographer
@MetehanToksoy, you have to keep track of the Ringtone instance, for example, as a class variable. Then you can do something like myRingtone.stop() later on.Gean
Good! this is used to play simple ringtone like we can play alarm sound, notification and more...!Procathedral
C
68

If a user has never set an alarm on their phone, the TYPE_ALARM can return null. You can account for this with:

Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

if(alert == null){
    // alert is null, using backup
    alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // I can't see this ever being null (as always have a default notification)
    // but just incase
    if(alert == null) {  
        // alert backup is null, using 2nd backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);                
    }
}
Cornwallis answered 16/4, 2011 at 14:8 Comment(2)
The URI returned might not be null even though it does not point to a valid sound. You should test the return value of RingtoneManager.getRingtone() for null instead/as-wellInterview
In 2017, not working failing to ring. Do you have it working in recent Android?Sheena
H
67

This is the way I've done:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.start();

It is similar to markov00's way, but uses MediaPlayer instead of Ringtone which prevents interrupting other sounds, like music, that might already be playing in the background.

Heterography answered 24/11, 2013 at 17:46 Comment(3)
I tried the top answer (ringtone.play) but the sound may get cut off. I used this approach and it worked perfectly.Chabazite
This is a better solution for anyone using any other audio components in their app.Varian
@YumYumYum, I just tested and it works. I did nothing but put the above code into my setOnClickListner. What did you do?Readability
K
17

Your example is basically what I'm using. It never works on the emulator, however, because the emulator doesn't have any ringtones by default, and content://settings/system/ringtone doesn't resolve to anything playable. It works fine on my actual phone.

Karp answered 11/4, 2010 at 20:37 Comment(0)
S
16

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

Shillyshally answered 31/3, 2017 at 13:24 Comment(0)
G
13

This works fine:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
MediaPlayer thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

try {
    thePlayer.setVolume((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)),
                        (float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)));
} catch (Exception e) {
    e.printStackTrace();
}

thePlayer.start();
Gardell answered 13/9, 2013 at 8:43 Comment(5)
Why are you dividing the volume by 7.0 ? Is it a commonly known working value or something you dig out yourself ?Romona
Something I dug out... :DGardell
Why do you do Float.parseFloat(Double.toString(....))?? Going through a String instance because you want a double->float conversion? Why do you do this?Myocardiograph
This part is redundant Uri.parse(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)), getDefaultUri() return a URI already, no need to parse it yet into another URIAtomics
7 is a max volume for the stramHigherup
N
13

It may be late but there is a new simple solution to this question for who ever wants it.
In kotlin

import android.provider.Settings
val player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI)
player.start()

Above code will play default ringtone but if you want default alarm, change

Settings.System.DEFAULT_RINGTONE_URI

to

Settings.System.DEFAULT_ALARM_ALERT_URI

Nesselrode answered 2/8, 2020 at 4:37 Comment(2)
you save my day!Moody
Some devices need permissions for Settings.System.DEFAULT_RINGTONE_URIUpbraiding
L
9

You can push a MP3 file in your /sdcard folder using DDMS, restart the emulator, then open the Media application, browse to your MP3 file, long press on it and select "Use as phone ringtone".

Error is gone!

Edit: same trouble with notification sounds (e.g. for SMS) solved using Ringdroid application

Lobule answered 15/9, 2010 at 17:6 Comment(0)
E
5
public class AlarmReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        //this will update the UI with message
        Reminder inst = Reminder.instance();
        inst.setAlarmText("");

        //this will sound the alarm tone
        //this will sound the alarm once, if you wish to
        //raise alarm in loop continuously then use MediaPlayer and setLooping(true)
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();

        //this will send a notification message
        ComponentName comp = new ComponentName(context.getPackageName(),
                AlarmService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}
Ehudd answered 16/4, 2015 at 10:30 Comment(1)
where does AlarmService come from?If
A
3

You could use this sample code:

Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtoneSound = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri)

if (ringtoneSound != null) {
    ringtoneSound.play();
}
Autobahn answered 31/3, 2015 at 17:26 Comment(0)
C
2

Copying an audio file to the sd card of the emulator and selecting it via media player as the default ringtone does indeed solve the problem.

Cordalia answered 5/10, 2010 at 16:56 Comment(0)
D
1

You can use the below code;

val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
// for alarm
// val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val ringtoneSound: Ringtone = RingtoneManager.getRingtone(requireContext(), ringtoneUri)
    ringtoneSound.play()

for stop;

ringtoneSound.stop()
Dole answered 9/6, 2021 at 7:29 Comment(0)
E
-3

Here's some sample code:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), notification);
mediaPlayer.start();
Eyeopening answered 16/7, 2014 at 9:12 Comment(3)
Explain the code with a little explanatin, Code only answers are not appreciated.Ensiform
Come on man, you never read the answers above probably. https://mcmap.net/q/136746/-how-to-play-ringtone-alarm-sound-in-androidKoonce
This is basically identical with this answer, but with the variable name mediaPlayer instead of mp.Wymore

© 2022 - 2024 — McMap. All rights reserved.