无论设备音量如何,均可播放声音

rom*_*lst 9 android

因此,在我的2.3设备上,即使设备音量设置为0 /静音,我也可以使用SoundPool或MediaPlayer以全音量播放声音.我的理解是你必须手动获取设备级别并在播放声音时设置它.

这就是我希望行为的工作方式.

但是,我现在在4.0设备上注意到声音是在设备的设定级别自动播放的,这是我不想要的!

这是OS版本之间的区别吗?如果是这样,有没有办法忽略设备音量?因此即使它静音,我也可以发出声音并让它被听到?

我不知道为什么我需要这个功能,但我真的很喜欢.

谢谢!

Jas*_*ley 17

我对闹钟应用有类似的需求.以下是相关代码以及有关卷的注释.

当声音配置文件设置为静音,当手动将警报流量设置为零并且铃声音量设置为零时,此功能适用于我的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();
    }
Run Code Online (Sandbox Code Playgroud)