2016-02-12 72 views
0

第一次按下按鈕時,播放通過AVAudioPlayer播放聲音時出現問題。當我再次點擊它時,它工作正常。AVAudioPlayer不能播放第一次

這裏是我使用的代碼,這是被稱爲在我viewDidLoad中()

func loadSounds(){ 
    do{ 
     try audioPlayerL = AVAudioPlayer(contentsOfURL: startListening!) 
     try audioPlayerE = AVAudioPlayer(contentsOfURL: doneListening!) 
    } 
    catch{ 

    } 
    audioPlayerL.delegate = self 
    audioPlayerL.prepareToPlay() 
    audioPlayerE.delegate = self 
    audioPlayerE.prepareToPlay() 
} 

這裏是播放文件

func playSound(){ 
    if(startedListening == true){ 
     audioPlayerL.play() 
    } 
    else{ 
     audioPlayerE.play() 
    } 
} 

的方法我絕對不知道爲什麼它不是第一次玩。在模擬器上它沒有任何問題。運行在我的iPhone 6上,第一次失敗。

我檢查過,它不會在任何地方發生錯誤。

+2

嘗試解決方法AVAudioSession,d其他玩家可能會發生衝突。在創建玩家之前,嘗試啓用混合會話。 '[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];' – markov

+0

實際上它做了謝謝! – NoSixties

回答

1

就這樣封閉,任何有同樣問題的人都知道這個問題已經解決了。像馬爾可夫說,這是固定通過添加這行代碼

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)

總看起來像這樣

一段代碼,加載聲音

func loadSounds(){ 
    do{ 
     try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) 
     try audioPlayerL = AVAudioPlayer(contentsOfURL: startListening!) 
     try audioPlayerE = AVAudioPlayer(contentsOfURL: doneListening!) 
    } 
    catch{ 
     print("error") 
    } 
    audioPlayerL.delegate = self 
    audioPlayerL.prepareToPlay() 
    audioPlayerE.delegate = self 
    audioPlayerE.prepareToPlay() 
} 

方法正在被調用以播放聲音

func playSound(){ 
    if(startedListening == true){ 
     audioPlayerL.play() 
    } 
    else{ 
     audioPlayerE.play() 
    } 
}