因此,在我的2.3设备上,即使设备音量设置为0 /静音,我也可以使用SoundPool或MediaPlayer以全音量播放声音。我的理解是你必须手动获取设备级别并在播放声音时设置它。
这就是我希望行为发挥作用的方式。
但是,我现在在4.0设备上注意到声音是在设备的设定级别自动播放的,这是我不想要的!
这是操作系统版本之间的差异吗?如果是这样,有没有办法忽略设备音量?所以,即使它被静音,我也能发出声音并让它被听到?
我无法理解为什么我需要这个功能,但我真的很喜欢。
谢谢!
答案 0 :(得分:16)
我对闹钟应用有类似的需求。以下是相关代码,其中包含有关音量的注释。
当声音配置文件设置为静音,当手动将闹钟流音量设置为零并且铃声音量设置为零时,此功能适用于我的HTC Rezound Android版本4.0.3。
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's 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's 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();
}
答案 1 :(得分:1)
从原始文件夹播放音乐的简便方法;
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();
}