2017-04-26 118 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) 
} 
相關問題