Reputation: 2533
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.
Upvotes: 1
Views: 635
Reputation: 2533
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()
}
}
Upvotes: 1