简体   繁体   中英

How to play ringtone selected from RingtonePreference

I am trying to play a ringtone which is selected from a RingtonePreference. How can I play it?

Here is my xml file code

<RingtonePreference
    android:title="Choose Alarm"
    android:key="ringtone"
    android:summary="this is summary"
    ></RingtonePreference>

Here is what I am doing in java

SharedPreferences getAlarms = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String alarms = getAlarms.getString("ringtone", "default ringtone");

When I use toast like this

Toast.makeText(getApplicationContext(), alarms, Toast.LENGTH_LONG).show();

Then it shows this kind of path

content://media/internal/audio/media/50

But I do not know how to play this one.

Help Please.

private void alarm(){
    SharedPreferences getAlarms = PreferenceManager.
                                  getDefaultSharedPreferences(getBaseContext());
    String alarms = getAlarms.getString("ringtone", "default ringtone");
    Uri uri = Uri.parse(alarms);
    playSound(this, uri);

    //call mMediaPlayer.stop(); when you want the sound to stop
}


private MediaPlayer mMediaPlayer;
private void playSound(Context context, Uri alert) {
        mMediaPlayer = new MediaPlayer();
        try {
            mMediaPlayer.setDataSource(context, alert);
            final AudioManager audioManager = (AudioManager) context
                    .getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        } catch (IOException e) {
            System.out.println("OOPS");
        }
    }

This here should be what you want :) I hope it works

Here is a sample project from Commonsware for the same you can download and check its working.

You can get the Uri from the String that you are getting by using,

SharedPreferences getAlarms = PreferenceManager.
                                  getDefaultSharedPreferences(getBaseContext());
String alarms = getAlarms.getString("ringtone", "default ringtone");
Uri uri = Uri.parse("alarms");

Then you can play the uri using MediaPlayer .

You can take preferred ringtone from preferences and You can easily play the ringtone using RingtoneManager class

SharedPreferences getAlarms = PreferenceManager.
                              getDefaultSharedPreferences(getBaseContext());
String alarms = getAlarms.getString("ringtone", "default ringtone");
Uri uri = Uri.parse(alarms);

Ringtone r = RingtoneManager.getRingtone(context, uri);
r.play();

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