简体   繁体   中英

Ringtone class not playing sound in android

I am using Ringtone class to play sound on message send. But Ringtone not playing sound on some devices like Motorola Turbo Droid. I am using Ringtone class like this.

Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+  mContext.getPackageName() + "/" + R.raw.send_sound);
Ringtone ringtone = RingtoneManager.getRingtone(mContext, uri);
ringtone.play();

I am using media player to play the mp3 file from raw folder and it works perfectly.

public class DummyActivity extends AppCompatActivity {

    MediaPlayer mPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dummy);
        playSound()
}
void playSound() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.reset();
        }
        mPlayer = MediaPlayer.create(DummyActivity.this, R.raw.bubble);
        mPlayer.start();
    }

or you can ringtone class like this

try {
  Uri path = Uri.parse("android.resource://"+getPackageName()+"/raw/sound.mp3");
  // The line below will set it as a default ring tone replace
  // RingtoneManager.TYPE_RINGTONE with RingtoneManager.TYPE_NOTIFICATION
  // to set it as a notification tone
  RingtoneManager.setActualDefaultRingtoneUri(
                    getApplicationContext(), RingtoneManager.TYPE_RINGTONE,
                    path);//Optional

  Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path); 
  r.play();
 } 
catch (Exception e) {
 e.printStackTrace(); 
}

Thanks, Happy Coding.....

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