我正在开发音乐播放器应用程序,我使用了NSProgressIndicator的歌曲时间轴,我如何才能在NSProgressIndicator中添加拇指?我试着添加NSSlider,但是我不能隐藏滑块而只显示拇指,有什么建议吗?
发布于 2021-09-29 14:49:13
实际上,如果没有更多关于你想要实现什么的信息,给你一个完整的答案并不容易。
最好的做法可能是完全避免使用NSProgressIndicator,而使用NSSlider,正如您在问题中提到的那样。
然后,您可以设置一个periodicTimeObserverForInterval (我假设您正在使用AVPlayer播放您的歌曲?)并根据歌曲时间线上的到达点改变滑块值。
最后,您应该有一个函数,该函数在每次用户更改滑块值时执行,该函数根据用户输入更改时间轴上的当前位置。
下面是我会怎么做:
// Assuming you have a player instance of type AVPlayer in your ViewController
// var player = AVPlayer()
// Move the slider to reflect the current timeline position
func setupPlayer() {
let interval = CMTime(value: 1, timescale: 2)
player.addPeriodicTimeObserverForInterval(interval, queue: Dispatch.main) { progress in
let seconds = CMTimeGetSeconds(progressTime)
if let duration = self.player.currentItem?.duration {
// Get the number of seconds of the whole file
let durationSeconds = CMTimeGetSeconds(duration)
self.slider.value = Float(seconds / durationSeconds)
}
}
}
// Change the current timeline position according to the user input
func setupSlider() {
slider.addTarget(self, action: #selector(slider_valueChanged), for: .valueChanged)
}
@objc func slider_valueChanged() {
if let duration = player.currentItem?.duration {
let totalSeconds = CMTimeGetSeconds(duration)
let value = Float64(slider.value) * totalSeconds
let seekTime = CMTime(value: Int64(value), timescale: 1)
player.seek(to: seekTime) { completedSeek in
// Add code here if you need to do something after the time was seeked
}
}
}如果您使用AVAudioPlayer播放音乐,那么我建议您切换到AVPlayer或使用NStimer,因为AVAudioPlayer不像this answer points out那样附带addPeriodicTimeObserverForInterval方法。
资源
https://stackoverflow.com/questions/69377871
复制相似问题