首页 > 解决方案 > 即使 iPhone 处于静音状态,AVAudioPlayer 仍在播放环境声音

问题描述

我有一个可观察的对象,它为我的应用程序提供了在我需要时(重复地)播放相同的铃声的功能。

问题是它在 iPhone 处于静音状态时播放,我无法停止它。我尽可能多地在 Google 上搜索,发现人们建议将音频类别设置为“环境”,但是,这似乎仍然无法解决我的问题。

这是我的编钟课:

class Chime: ObservableObject {
    
    let chimeSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "chime.wav", ofType: nil)!)
    
    private var audioPlayer: AVAudioPlayer?
    
    init() {
        let audioSession = AVAudioSession.sharedInstance()

        do {
            try audioSession.setCategory(.ambient, options: .duckOthers)
            try audioSession.setActive(true)
        } catch {
            print("Failed to activate audio session: \(error.localizedDescription)")
        }

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: chimeSoundUrl)
            audioPlayer?.prepareToPlay()
            audioPlayer?.volume = 1.0
        } catch {
            print("Failed to prepare audio player: \(error.localizedDescription)")
        }
    }
    
    func play() {
        audioPlayer?.currentTime = 0
        audioPlayer?.play()
    }
}

我已经尝试在 Chime 类的 init 函数中设置音频类别,在应用程序的顶层在播放铃声的视图的 onAppear 中,以及在 Chime 类的“播放”方法中(这实际上会导致应用程序性能问题) - 这些似乎都不起作用。

我真的很感激任何帮助。谢谢

标签: iosswiftavaudioplayeravaudiosession

解决方案


不确定您是否在真实设备上尝试过,但这是我发现的:

使用模拟器,如果在打开应用程序时静音开关已经处于活动状态,它的行为就好像它没有处于静音状态并播放声音。如果在打开应用程序后激活静音开关,它会按预期工作。

当我尝试在真实设备上运行它时,它在两种情况下都能正常工作,所以可能是模拟器中的错误

如果您只是播放短警报类型的声音,您可能应该使用音频服务而不是 AVAudioPlayer。这可能看起来像这样:

class Chime {

    let chimeSoundUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "alert.mp3", ofType: nil)!)
    let chimeSoundID: SystemSoundID

    init(){
        var soundID:SystemSoundID = 0
        AudioServicesCreateSystemSoundID(chimeSoundUrl as CFURL, &soundID)
        chimeSoundID = soundID
    }

    func play(){
        AudioServicesPlaySystemSound(chimeSoundID)
    }
    
}

在模拟器中运行上述程序,静音开关没有效果,声音总是播放,在真实设备上它按预期工作。


推荐阅读