我正在使用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)
}
我做错了吗?
答案 0 :(得分:0)
修复方法是使用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)
}