xcode 如何以编程方式使我的应用静音(禁用声音)

cvxl0en2  于 2023-06-07  发布在  其他
关注(0)|答案(3)|浏览(434)

我在做一个隐藏广告的应用浏览器快好了有时浏览器会自动播放声音(可能是JavaScript驱动的)
现在我需要关闭此应用程序中的所有声音。我试过两种方法:通过AVFoundation和WebKit。
请帮助我得到的想法,我如何能做到这一点。更多的变化是受欢迎的:)

jxct1oxe

jxct1oxe1#

这可以通过MediaPlayer模块完成:

(MPVolumeView().subviews.filter{ NSStringFromClass($0.classForCoder) == "MPVolumeSlider" }.first as? UISlider)?.setValue(0, animated: false)

请注意您可以更改的两个值:

value: how much volume you want (0 in this case)
animated: allowing you to animate the change visually
i2loujxw

i2loujxw2#

Swift 5 / Xcode 11
第一步:

import MediaPlayer

第二步:

let slider = MPVolumeView().subviews.first(where: { $0 is UISlider }) as? UISlider

第三步:

slider?.setValue(0.0, animated: false)
9jyewag0

9jyewag03#

这对我很有效

//isMuted is a variable i use to check for the mute mode 
if isMuted == true {
        do {
            try AVAudioSession.sharedInstance().setCategory(.ambient, 
                mode: .default, options: .mixWithOthers)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print(error)
        }
        
    }
    else {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print(error)
        }
    }

相关问题