Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Run multiple audio in sequence one by one in loop in swift

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()
    }
}
question from:https://stackoverflow.com/questions/65886201/run-multiple-audio-in-sequence-one-by-one-in-loop-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...