Mute the global sound in Android

前端 未结 6 1112
心在旅途
心在旅途 2020-12-02 20:49

Is there a method that can be used to mute the global sound from an application button?

6条回答
  •  旧时难觅i
    2020-12-02 21:22

    Technically there is no such thing as a global volume. Bhargav's answer should put you on the right track. There are many different "streams" that can be controlled by the AudioManager class, namely Music, Ringer, In-Call, Alarm, Notification, System and DMTF. You have to set the volume for all of these individual streams to 0, which is an incredibly simple process as Bhargav as shown.

    Just create an Audiomanager object:-

    AudioManager audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
    

    And then use it to change the volume for all the streams:-

    audioManager.setStreamVolume(AudioManager.Stream, Extra Flags or null);
    

    Instead of typing AudioManager.Stream, type "AudioManager." and press Ctrl+Space Bar to see all of the different streams you can use. Check the documentation for the many different types of flags that can add a sound or a vibration or bring up the volume UI when the volume is changed.

    Each stream may have a different maximum volume so be sure to use getMaxStreamVolume to get the maximum values and set the volume accordingly in case you are using a single value to edit all the streams. So if the user wants to set global volume to 50%, get the maximum volume for each stream, multiply them by 0.5, and set it to the corresponding streams.

提交回复
热议问题