简体   繁体   中英

AVAudioPlayer doesn't play the first time

I'm having a problem with playing a sound through the AVAudioPlayer when a button is pressed for the first time. When I tap it again it works fine.

Here is the code I'm using, this is being called in my 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()
}

Here is the method that plays the file

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

I have absolutely no clue why it isn't playing the first time around. On the emulator it works without any problems. Running on my iPhone 6 plus it fails the first time around.

I checked and it doesn't throw an error anywhere either.

Just so this is closed up and anyone who has the same problem knows this was solved. Like Markov said it was fixed by adding this line of code

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

The total looks like this

piece of code that loads the sounds

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()
}

method that is being called to play the sounds

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM