AVAudioPlayer time display

前端 未结 2 1267
走了就别回头了
走了就别回头了 2021-02-06 16:39

I have a simple mp3 playing through AVAudioPlayer and I want to be able to display how much time is left.

I know the answer includes subtracting AVAudioPlayer.dur

相关标签:
2条回答
  • 2021-02-06 16:45

    I would go for an NSTimer. Schedule it to run every second while the media is played and so you can keep your UI updated with the time left.

    // Place this where you start to play
    NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                         target:self
                                                       selector:@selector(updateTimeLeft)
                                                       userInfo:nil
                                                        repeats:YES];
    

    And create the method to update you UI:

    - (void)updateTimeLeft {
        NSTimeInterval timeLeft = self.player.duration - self.player.currentTime;
    
        // update your UI with timeLeft
        self.timeLeftLabel.text = [NSString stringWithFormat:@"%f seconds left", timeLeft];
    }
    
    0 讨论(0)
  • 2021-02-06 17:04

    I use it in swift and it work:

    // this for show remain time
    let duration = Int((player1?.duration - (player1?.currentTime))!)
    let minutes2 = duration/60
    let seconds2 = duration - minutes2 * 60
    durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String
    
    //this for current time
    let currentTime1 = Int((player1?.currentTime)!)
    let minutes = currentTime1/60
    let seconds = currentTime1 - minutes * 60
    curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
    
    0 讨论(0)
提交回复
热议问题