Reputation: 37
I want to run multiple audios in a loop. So I want to stop the execution of loop until the completion of running audio.
I have tried semaphores but no luck. Should I have to run it on main thread or what?
@IBAction func btnPlayAudiosClicked(_ sender: Any) {
for each in Constants.audioNames{
semaphore.wait()
txtStatus.text = "Playing audio " + each
AudioManager.shared.playSound(audioName: each)
semaphore.signal()
}
}
Upvotes: 0
Views: 402
Reputation: 1863
import AVFoundation
class YourClass: ..., AVAudioPlayerDelegate {
var player: AVAudioPlayer?
var yourURLStrings:[String] = []
override func viewDidLoad() {
self.playSound(position: 0)
}
func playSound(position: Int) {
let firstURL = yourURLStrings[position]
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
//Set delegate to self so we can execute delegate `AVAudioPlayerDelegate` functions
player.delegate = self
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
self.yourURLStrings.remove(at: 0)
if(yourURLStrings.count > 0) {
self.playSound(position: 0)
}
}
}
Upvotes: 1