【问题标题】:Run multiple audio in sequence one by one in loop in swift快速循环运行多个音频
【发布时间】:2021-01-25 13:58:57
【问题描述】:

我想循环播放多个音频。所以我想停止循环的执行,直到运行音频完成。

我尝试过信号量,但没有运气。我应该在主线程上运行它还是什么?

   @IBAction func btnPlayAudiosClicked(_ sender: Any) {
    for each in Constants.audioNames{
        semaphore.wait()
        
        txtStatus.text = "Playing audio " + each
        AudioManager.shared.playSound(audioName: each)
        
        semaphore.signal()
    }
}

【问题讨论】:

  • So I want to stop the execution of loop until the completion of running audio. 是什么意思?
  • 我希望一个音频完全播放,然后另一个应该播放。但在这种情况下循环执行,不要等待音频完成。
  • Semaphore 用于锁定数据,因此其他对象无法访问它......它与等待某事完成无关
  • 那么在这种情况下可以做什么。

标签: swift loops avfoundation avkit


【解决方案1】:
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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多