How to play ringtone selected from RingtonePreference

北战南征 提交于 2019-12-04 19:37:35

问题


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.


回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/10460499/how-to-play-ringtone-selected-from-ringtonepreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!