[英]Swift - AVAudioPlayer still playing sound when device is on silent?
我正在制作一個相當基本的應用程序並且一直在探索使用AVAudioPlayer在我的應用程序中播放聲音,但是我遇到了一個問題,即使設備處於靜音狀態時它也能發出聲音。 這是我正在使用的代碼:
var audioPlayer = AVAudioPlayer()
然后在View中加載:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
var beepOne = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("menu", ofType: "wav")!)
audioPlayer = AVAudioPlayer(contentsOfURL: beepOne, error: &error)
audioPlayer.prepareToPlay()
當聲音播放時:
audioPlayer.play()
當設備處於靜音狀態或切換到靜音狀態時,我需要做些什么才能停止播放聲音? 也許在audioPlayer.play()
之前,if語句檢測設備是否處於靜默狀態?
在第二行和第三行代碼中找到了錯誤:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
我不得不將AVAudioSessionCategoryPlayback
更改為AVAudioSessionCategoryAmbient
希望這有助於其他可能遇到同樣問題的人:)
我想使用swift 2.0添加一個解決方案,需要try / catch錯誤處理。 有一個關於這個偉大的文章在這里 。
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryAmbient, withOptions: .DuckOthers)
} catch {
print("AVAudioSession cannot be set")
}
這篇文章是為了在手機靜音時使音頻播放靜音。 我想做相反的事情,如果用AVAudioSessionCategoryPlayback替換上面的AVAudioSessionCategoryAmbient,即使手機靜音,你的音頻也會播放。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.