ios - 即使 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 类的“播放”方法中(这实际上会导致应用程序性能问题) - 这些似乎都不起作用。
我真的很感激任何帮助。谢谢
解决方案
不确定您是否在真实设备上尝试过,但这是我发现的:
使用模拟器,如果在打开应用程序时静音开关已经处于活动状态,它的行为就好像它没有处于静音状态并播放声音。如果在打开应用程序后激活静音开关,它会按预期工作。
当我尝试在真实设备上运行它时,它在两种情况下都能正常工作,所以可能是模拟器中的错误。
如果您只是播放短警报类型的声音,您可能应该使用音频服务而不是 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)
}
}
在模拟器中运行上述程序,静音开关没有效果,声音总是播放,在真实设备上它按预期工作。
推荐阅读
- python - 颜色取决于 (x,y,z) 的参数化 3D 曲面图
- android - 绘制到 FrameBuffer 会导致 Y 反转
- html - 如何解决 Outlook 2016 未正确显示 HTML 模板的问题?
- google-apps-script - 附加触发器的重复间隔必须至少为一小时
- java - 使用 S3 存储桶名称查找 AWS 账户 ID
- java - 获取没有客户端 ID 的 kafka 主题指标
- jquery - 轮播中的指示器不工作,幻灯片效果也不起作用
- excel - 如何在调用不同的 Excel 宏时显示状态消息?
- python - “按钮”.config() 在我的代码中不起作用
- r - 在 R 中创建 ggplot() 时更改子图例中的文本