是否有人可以通过教程链接向AVAudioPlayer添加播放进度条?
我在这个网站和谷歌上广泛搜索无济于事
我想通了,也不算太糟糕。
只需在计时器中更新它
playbackTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(myMethod:)
userInfo:nil
repeats:YES];
}
-(void)myMethod:(NSTimer*)timer {
float total=audioPlayer.duration;
float f=audioPlayer.currentTime / total;
NSString *str = [NSString stringWithFormat:@"%f", f];
playbackProgress.progress=f;
NSLog(str);
}
添加一个定期时间观察器并更新滑块 - 在Swift中它将是这样的 -
func addPlayBackSlider()
{
playbackSlider = UISlider(frame:CGRect(x:10, y:300, width:300, height:20))
playbackSlider?.minimumValue = 0
let duration : CMTime = playerItem.asset.duration
let seconds : Float64 = CMTimeGetSeconds(duration)
playbackSlider?.maximumValue = Float(seconds)
playbackSlider?.isContinuous = true
//If you want to manually set progressBar
playbackSlider?.addTarget(self, action: #selector(AddAudioController.playbackSliderValueChanged(_:)), for: .valueChanged)
//Here is the Observer
player!.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: DispatchQueue.main) { (CMTime) -> Void in
if self.player!.currentItem?.status == .readyToPlay {
let time : Float64 = CMTimeGetSeconds(self.player!.currentTime());
self.playbackSlider!.value = Float ( time );
}
}
}
//If you want to manually set progressBar
func playbackSliderValueChanged(_ playbackSlider:UISlider)
{
let seconds : Int64 = Int64(playbackSlider.value)
targetTime = CMTimeMake(seconds, 1)
print(targetTime)
player!.seek(to: targetTime)
if player!.rate == 0
{
player?.play()
playButton!.setTitle("Pause", for: UIControlState.normal)
}
}
CADisplayLink
类,一旦屏幕重绘发生,就会自动调用您定义的方法
Timer
不提供精确的射击,并且可以比请求的更新更早或更晚漂移,也不知道屏幕重绘,因此在屏幕重绘刚刚发生后可能会快乐地发射10ms。
let displayLink = CADisplayLink(target: self,
selector: #selector(update))
displayLink.add(to: .current, forMode: .common)
@objc func update() {
let currentTime = avAudioPlayer.currentTime
let totalTime = avAudioPlayer.duration
let progress = currentTime / totalTime
}