Reputation: 417
So, I have a for loop that runs values from an array into an if statement. The if statement plays a sound depending on the value in the array.
However, right now, all the values are being run through at once, so the sounds are all played at the same time. Here's what my code looks like right now:
// sortedKeys is an array made from the keys in the newData dictionary.
let sortedKeys = Array(newData.keys).sort(<)
// newData is the dictionary of type [float:float] being used to get the values that are then being run through the if statement.
for (value) in sortedKeys {
let data = newData[value]
if data <= Float(1) {
self.audioPlayer1.play()
} else if data <= Float(2) && data > Float(1) {
self.audioPlayer2.play()
} else if data <= Float(3) && data > Float(2) {
self.audioPlayer3.play()
} else if data <= Float(4) && data > Float(3) {
self.audioPlayer4.play()
} else if data <= Float(5) && data > Float(4) {
self.audioPlayer5.play()
} else if data <= Float(6) && data > Float(5) {
self.audioPlayer6.play()
} else if data <= Float(7) && data > Float(6) {
self.audioPlayer7.play()
} else if data <= Float(8) && data > Float(7) {
self.audioPlayer8.play()
} else if data <= Float(9) && data > Float(8) {
self.audioPlayer9.play()
} else {
self.audioPlayer10.play()
}
}
How can I make it so that once the AVAudioPlayer
finishes playing, I continue the for loop to get the next sound? I'm thinking it has something to do with AVPlayerItemDidPlayToEndTimeNotification
, but I don't know how to use this to delay the for loop.
Thanks!
Upvotes: 2
Views: 1203
Reputation: 1723
I had a similar issue and used the sleep(insert number of seconds to pause) e.g. sleep(3) function after the self.audioPlayer.play() function in order to give the play function time to play. It is not ideal though as it blocks the main thread.
Upvotes: 2
Reputation: 124997
How can I make it so that once the AVAudioPlayer finishes playing, then I continue the for loop to get the next sound.
Have the audio player's delegate implement -audioPlayerDidFinishPlaying:successfully:
such that it selects the next sound and plays it.
Audio is played asynchronously, so you can't just have your code pause for a bit while the sound plays and then continue on. You need to design your code so that it fires off the sound, and then when the audio player says it's finished, the next sound is started.
Upvotes: 2