我正在使用AVPlayer播放mp3文件。我使用它而不是AVAudioPlayer,因为它支持以0.0 ... 2.0
范围之外的速度播放。但是,我希望音频不断循环播放,因此我正在使用AVQueuePlayer和AVPlayerLooper播放文件。当rate
属性为正时,此方法有效,但是当反向回放到达文件的开头时,它只是停止,而不是返回文件末尾并继续反向播放。有什么方法可以让播放器循环播放?这是我正在尝试的内容:
override func viewDidLoad() {
super.viewDidLoad()
//Initialize the audio file and audio player
guard let path = Bundle.main.path(forResource: "sideAMusic.mp3", ofType: nil) else {
Console.log("Uh oh - no path could be found for filename: \("sideAMusic")")
return
}
let url = URL(fileURLWithPath: path)
let playerItem = AVPlayerItem(url: url)
self.sideAPlayer = AVQueuePlayer(playerItem: playerItem)
sideALooper = AVPlayerLooper(player: sideAPlayer!, templateItem: playerItem)
sideAPlayer?.volume = 1
sideAPlayer?.play()
}
// Use a slider in the range of -4 ... 4 to set the playback speed
@IBAction func speedSlider(_ sender: UISlider) {
self.sideAPlayer?.rate = sender.value
}
您应该添加一个定期的时间观察者。这是文档的link。
您还应该检查here如何观察时间。
另外,这是一个代码示例。
func addPeriodicTimeObserver() {
// Notify every 0.05 second
let timeScale = CMTimeScale(NSEC_PER_SEC)
let time = CMTime(seconds: 0.05, preferredTimescale: timeScale)
timeObserverToken = player.addPeriodicTimeObserver(forInterval: time,
queue: .main) {
[weak self] currentTime in
if CMTimeCompare(currentTime, CMTime.zero) == 0 {
//The track reached the beginning, you should seek player to the end time
self?.player.seek(to: self?.playerItem.duration, toleranceBefore: .zero, toleranceAfter: .zero)
self?.player.play()
}
}
}
func removePeriodicTimeObserver() {
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}