Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
Om3ga Avatar asked May 05 '12 09:05

Om3ga


1 Answers

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

like image 58
FabianCook Avatar answered Sep 21 '22 06:09

FabianCook