当静音模式开启时,声音仍然会播放。

3

我正在使用AudioServicesPlaySystemSoundWithCompletion播放系统声音,使用AVAudioPlayer播放自定义声音。

如果静音开关打开,为什么还会播放声音?我尝试了所有“AVAudioSession”的类别。

我尝试了以下代码:

 try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
 try AVAudioSession.sharedInstance().setActive(true)

我也尝试过这个方法:

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)

我尝试了链接中定义的所有类别,但当手机静音(静音开关打开)时,声音仍然会播放。 https://developer.apple.com/reference/avfoundation/avaudiosession/audio_session_categories 我是这样播放声音的:
系统声音:
AudioServicesPlaySystemSoundWithCompletion(1304, nil)

自定义声音:

        let url = Bundle.main.url(forResource: "sound01", withExtension: ".wav")
        do {
            if audioPlayer != nil {
                audioPlayer!.stop()
                audioPlayer = nil
            }
            if let soundURL = soundURL {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
                try AVAudioSession.sharedInstance().setActive(true)
                audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            }
            guard let audioPlayer = audioPlayer else {
                return
            }
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch let error {
            print(error.localizedDescription)
        }

我做错了什么吗?


编辑你的问题并包括你是如何播放声音的。 - Daniel Storm
@DanielStorm 我刚刚更新了。谢谢。 - user3427013
1个回答

3
修复方法是使用AudioServicesPlayAlertSound函数而不是AudioServicesPlaySystemSoundWithCompletion函数。我们也不能使用AVAudioPlayer。我们需要通过为每个自定义声音创建一个声音ID来使用AudioServicesPlayAlertSound函数。
let soundURL = Bundle.main.url(forResource: "test01", withExtension: ".wav")

if let soundURL = soundURL {
      var soundID : SystemSoundID = 0
      AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID)
      AudioServicesPlayAlertSound(soundID)
}

你能帮忙解决这个问题吗?https://stackoverflow.com/questions/70875385/why-sound-still-play-when-devices-silent-mode-is-on/70875992#70875992 - Kishan Bhatiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接