How to play ringtone selected from RingtonePreference

梦想与她 提交于 2019-12-03 12:45:24
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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!