2017-04-26 120 views
1

我使用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) 

我想在这个环节中定义的所有类别,但是当手机调成静音的声音总是打(无声开关ON)。 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

@DanielStorm我刚刚更新。谢谢。 – user3427013

回答

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) 
} 
相关问题