how to enable media sound even in silent mode

2019-05-11 15:53发布

问题:

how do i start the sound even in silent mode? i got my audio file in my raw folder. i've made some codes but when i go to sound settings of android the ringtone and alarm are the only ones that are changed to maximum but not the media part. here is my code

public void playSound(Context context)
{
    AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    int maxVolumeAlarm = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
    int maxVolumeRing = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
    audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolumeAlarm,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
    audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolumeRing,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);;
    MediaPlayer mMediaPlayer;
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer = MediaPlayer.create(context, R.raw.puff);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setLooping(false);
    mMediaPlayer.start();
}

回答1:

it's okay now, i used this code

AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    int maxVolumeMusic = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolumeMusic,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);