
Swift
AVPlayer - 为 CMTime 添加秒数
在使用 AVPlayer 进行音视频播放时,我们经常需要对时间进行处理,比如获取当前播放时间、设置播放进度等。而 AVPlayer 中表示时间的类型是 CMTime。CMTime 是一个 C 结构体,用于表示持续时间或时间点。它由两个成员组成:value 和 timescale。value 表示时间的数值,timescale 表示时间的刻度,用于计算时间的精度。我们可以通过将 value 除以 timescale 来获取时间的秒数。然而,有时候我们需要为一个 CMTime 对象添加一定的秒数。这可能是因为我们想要向前或向后调整播放进度,或者是为了计算一个相对时间点。下面我们将介绍如何为 CMTime 对象添加秒数。代码示例:Swiftextension CMTime { func adding(seconds: Double) -> CMTime { let secondsToAdd = CMTime(seconds: seconds, preferredTimescale: self.timescale) return self + secondsToAdd }}// 示例用法let currentTime = CMTime(seconds: 10, preferredTimescale: 1)let newTime = currentTime.adding(seconds: 5)print("原始时间:\(CMTimeGetSeconds(currentTime)) 秒")print("添加 5 秒后的时间:\(CMTimeGetSeconds(newTime)) 秒")实现原理:在上面的代码示例中,我们通过给 CMTime 对象加上一个新的 CMTime 对象来实现添加秒数的功能。新的 CMTime 对象表示要添加的秒数。我们首先通过将要添加的秒数转换为 CMTime 对象,确保 timescale 与原始 CMTime 对象一致,以免造成时间精度的损失。然后,我们通过将两个 CMTime 对象相加,得到一个新的 CMTime 对象,表示原始时间加上要添加的秒数。案例分析:假设我们正在开发一个音乐播放器应用。用户可以通过拖动进度条来调整播放进度。当用户向前拖动进度条时,我们需要为当前播放时间添加一定的秒数来实现快进功能。当用户向后拖动进度条时,我们需要为当前播放时间减去一定的秒数来实现快退功能。通过使用上述代码示例中的 adding(seconds:) 方法,我们可以很方便地实现这些功能。在播放器界面中,我们可以监听进度条的拖动事件,并根据拖动的距离调整播放时间。下面是一个简单的示例代码:Swiftclass PlayerViewController: UIViewController { @IBOutlet weak var progressBar: UISlider! private var player: AVPlayer! override func viewDidLoad() { super.viewDidLoad() // 初始化 AVPlayer let url = URL(string: "https://example.com/music.mp3")! let playerItem = AVPlayerItem(url: url) player = AVPlayer(playerItem: playerItem) // 监听进度条的拖动事件 progressBar.addTarget(self, action: #selector(progressBarValueChanged(_:)), for: .valueChanged) // 开始播放 player.play() } @objc private func progressBarValueChanged(_ sender: UISlider) { let secondsToAdd = Double(sender.value) // 根据进度条的值计算要添加的秒数 let currentTime = player.currentTime() let newTime = currentTime.adding(seconds: secondsToAdd) player.seek(to: newTime) }}在上面的示例代码中,我们监听了进度条的 valueChanged 事件,并将进度条的值转换为要添加的秒数。然后,我们获取当前播放时间 currentTime,并使用 adding(seconds:) 方法为其添加或减去相应的秒数,得到新的播放时间 newTime。最后,我们通过 seek(to:) 方法将播放器的播放位置设置为新的时间点。通过上述的代码示例,我们可以很方便地为 CMTime 对象添加一定的秒数,实现音视频播放器中的快进和快退功能。这样用户就可以更加灵活地控制音视频的播放进度了。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号