请问是否有教程链接,能够为AVAudioPlayer添加播放进度条?
我已经在本网站和谷歌上进行了广泛搜索,但没有找到相关内容。
请问是否有教程链接,能够为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);
}
CADisplayLink
类会在屏幕重新绘制时自动调用您定义的方法。
Timer
不能提供精确的触发时间,并且可能会比请求的更新时间早或晚,而且它也不知道屏幕重新绘制的情况,因此可能会在屏幕重新绘制后10毫秒才触发。
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
}
添加一个定期时间观察器并更新滑块 - 在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)
}
}
addPeriodicTimeObserver
方法。 - Enrique