- 要想在拖动进度条时播放声音,需要使用AVPlayer的addPeriodicTimeObserver方法定期检查当前的播放进度,然后根据需要进行声音处理。
var timeObserverToken: Any?
let player = AVPlayer()
// Add time observer to track the progress of the player
timeObserverToken = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] time in
guard let self = self else { return }
if self.player.rate > 0 {
// If the player is currently playing
if let currentItem = self.player.currentItem {
// Calculate the current playback progress in percentage
let currentPlaybackTime = currentItem.currentTime().seconds
let totalDuration = currentItem.duration.seconds
let progressPercentage = currentPlaybackTime / totalDuration
// Play sound based on the current progress percentage
if progressPercentage > 0.5 {
// Play sound if the playback progress is more than 50%
// Add your own sound file here
self.playSound(soundFile: "sound.mp3")
}
}
}
}
- 使用扩展实现播放声音的功能。
extension AVPlayer {
func playSound(on interval: TimeInterval, file: String) -> NSUUID? {
let interval = CMTimeMakeWithSeconds(interval, preferredTimescale: 600)
return addPeriodicTimeObserver(forInterval: interval, queue: nil, using: { (time) in
let trackTime = self.currentItem?.currentTime().seconds ?? 0
let trackDuration = self.currentItem?.duration.seconds ?? 0
let progress = trackTime / trackDuration
if progress > 0.5 {
// Add your own sound file here
let url = Bundle.main.url(forResource: file, withExtension: "mp3")!
let audioPlayer = try! AVAudioPlayer(contentsOf: url)
audioPlayer.prepareToPlay()
audioPlayer.play()
// Remove observer after playing the sound
self.remove