9

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.

4

3 回答 3

21
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");
        }
    }

这应该是你想要的:)我希望它有效

于 2012-05-05T09:58:21.403 回答
1

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.

于 2012-05-05T09:31:06.180 回答
0

您可以从首选项中获取首选铃声,您可以使用 RingtoneManager 类轻松播放铃声

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();
于 2015-04-21T02:47:59.113 回答