You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI:如何让VoiceOver不打断onAppear时播放的音频?

解决方法

1. 调整音频会话配置,兼容VoiceOver

修改AudioManager的音频会话设置,添加混音选项并监听播放完成事件,配合控制VoiceOver的朗读时机:

class AudioManager {
    static var shared = AudioManager()
    
    private let audioPlayer = AVQueuePlayer()
    private var wasVoiceOverRunning = false

    init() {
        let audioSession = AVAudioSession.sharedInstance()
        do {
            // 允许音频与VoiceOver同时播放,避免被直接打断
            try audioSession.setCategory(.playback, mode: .default, options: [.mixWithOthers])
            try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
        } catch {
            debugPrint(error)
        }
        
        // 监听音频播放完成通知
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil)
    }

    func playWelcomeMessage() {
        // 记录VoiceOver状态
        wasVoiceOverRunning = UIAccessibility.isVoiceOverRunning
        
        if wasVoiceOverRunning {
            // 暂停VoiceOver当前朗读
            UIAccessibilitySpeechSynthesizer.shared.stopSpeaking(at: .immediate)
        }
        
        let playerItem = AVPlayerItem(url: Audio.welcome.fileURL!)
        audioPlayer.insert(playerItem, after: nil)
        audioPlayer.play()
    }
    
    @objc private func playerDidFinishPlaying() {
        if wasVoiceOverRunning {
            // 音频结束后,触发VoiceOver重新朗读当前视图
            UIAccessibility.post(notification: .screenChanged, argument: nil)
        }
        // 清空播放队列,避免重复播放
        audioPlayer.removeAllItems()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

2. 完善视图的无障碍配置

确保视图的无障碍特性正确设置,配合音频播放逻辑:

FirstTimeLandingView(continueAction: {
    [...]
})
.onAppear {
    AudioManager.shared.playWelcomeMessage()
}
.accessibilityAddTraits([.startsMediaSession, .playsSound])
// 可选:设置明确的无障碍标签,让VoiceOver朗读更精准
.accessibilityLabel("欢迎来到应用,点击继续按钮开始使用")

3. 核心逻辑说明

  • 音频会话配置:.mixWithOthers选项允许你的音频与VoiceOver音频共存,.notifyOthersOnDeactivation会在音频会话结束时通知系统恢复其他音频(如VoiceOver)。
  • VoiceOver控制:播放音频前暂停VoiceOver当前朗读,避免冲突;音频结束后通过.screenChanged通知触发VoiceOver重新读取视图内容,保证无障碍体验不缺失。
  • 无障碍特性:.startsMediaSession告知VoiceOver当前视图启动了媒体会话,让系统调整朗读行为,配合自定义音频播放。

内容的提问来源于stack exchange,提问作者naudecruywagen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:55:36