问题描述
我想循环播放多个音频。所以我想停止循环的执行,直到运行音频完成。
我尝试过信号量,但没有成功。我应该在主线程上运行它还是什么?
@IBAction func btnPlayAudiosClicked(_ sender: Any) {
for each in Constants.audioNames{
semaphore.wait()
txtStatus.text = "Playing audio " + each
AudioManager.shared.playSound(audioName: each)
semaphore.signal()
}
}
解决方法
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)
}
}
}