Play sound regardless of device volume level

So, on my 2.3 devices, I can play sound from SoundPool or MediaPlayer at full volume, even if the volume of the device is set to 0 / mute. I realized that you had to manually get the level of the device and set it when playing sound.

This is how I want the behavior to work.

However, now I notice on my device 4.0 that sounds automatically play at the device set level, which I don’t want!

Is this the difference between OS versions? If so, is there a way to ignore the volume of devices? So even if it is muted, can I play a sound and hear it?

I can’t understand why I need this function, but I really do it.

Thanks!

+7
source share
2 answers

I had a similar need for an alarm application. Here is the relevant code with comments regarding the volume.

This works on my HTC Rezound Android version 4.0.3 when the sound profile is set to silent, when the volume of the alarm is manually set to zero, and when the volume of the ringtone is set to zero.

Context context; MediaPlayer mp; AudioManager mAudioManager; int userVolume; public AlarmController(Context c) { // constructor for my alarm controller class this.context = c; mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); //remeber what the user volume was set to before we change it. userVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM); mp = new MediaPlayer(); } public void playSound(String soundURI){ Uri alarmSound = null; Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); try{ alarmSound = Uri.parse(soundURI); }catch(Exception e){ alarmSound = ringtoneUri; } finally{ if(alarmSound == null){ alarmSound = ringtoneUri; } } try { if(!mp.isPlaying()){ mp.setDataSource(context, alarmSound); mp.setAudioStreamType(AudioManager.STREAM_ALARM); mp.setLooping(true); mp.prepare(); mp.start(); } } catch (IOException e) { Toast.makeText(context, "Your alarm sound was unavailable.", Toast.LENGTH_LONG).show(); } // set the volume to what we want it to be. In this case it max volume for the alarm stream. mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_PLAY_SOUND); } public void stopSound(){ // reset the volume to what it was before we changed it. mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, userVolume, AudioManager.FLAG_PLAY_SOUND); mp.stop(); mp.reset(); } public void releasePlayer(){ mp.release(); } 
+13
source

An easy and alternative way to play music from the source folder;

 try { String uri = "android.resource://" + getPackageName() + "/" + R.raw.beep; //Strign uri = "http://bla-bla-bla.com/bla-bla.wav" Uri notification = Uri.parse(uri); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } 
0
source

All Articles