AVAudioPlayer 播放进度

11

请问是否有教程链接,能够为AVAudioPlayer添加播放进度条?

我已经在本网站和谷歌上进行了广泛搜索,但没有找到相关内容。

3个回答

19

我理解了并且这并不太难。

只需在计时器中更新它即可。

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);
}

11

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
}

确实计时器不错,但是这种方法更适合跟踪。 - Muhammadjon

0

添加一个定期时间观察器并更新滑块 - 在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)
    }
}

希望这可以帮到你 :) - Shawon91
7
遗憾的是,加入周期性时间观察器只适用于AVPlayer,而不适用于AVAudioPlayer。 - Joshua Haines
3
AVAudioPlayer没有addPeriodicTimeObserver方法。 - Enrique

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接