Gerges Eid
Gerges Eid

Reputation: 1075

how to get current time in AVAudioplayer in a label while playing

I tried to build an app to play the MP3 files. I want to get current time and duration to show it in 2 labels while playing.

I used this code:

let duration = Int((player1?.duration)!)
let minutes2 = duration/60
let seconds2 = duration - minutes2 * 60
durLabel.text = NSString(format: "%02d:%02d", minutes2,seconds2) as String


let currentTime1 = Int((player1?.currentTime)!)
let minutes = currentTime1/60
let seconds = currentTime1 - minutes * 60
curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String

In duration it shows the half time of the song.

For example: If the duration of the song is 20 minutes and 40 seconds, it shows the half like that 10:20. But it did not make progress in the case of current time, it shows 00:00

Thanks at all.

Upvotes: 2

Views: 9974

Answers (4)

D'Fontalland
D'Fontalland

Reputation: 345

I had the same issue and to handle it I created a timer of 1 second for it. Then:

  1. Started at the same time we set the player to play.
  2. On timer tick, set a @published variable with the player.currentTime value.
  3. Invalidate the timer when the user stop or pause the player and when the audio finish playing.

Upvotes: 0

Masoud Roosta
Masoud Roosta

Reputation: 475

    // this is to compute and show remaining 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 is to show and compute 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

Upvotes: 7

Mohammad Mirzakhani
Mohammad Mirzakhani

Reputation: 620

If you have Slider to seek on mp3 file, like this :

    @IBOutlet weak var slidetOutlet: UISlider!

You can update your UILabel like this:

     self.lblPlayerTime.text = self.secondsToHoursMinutesSeconds(seconds: Double( self.slidetOutlet.value ))

to initial your Player and Slider :

func playerInit()  {
    guard let url = URL(string: urlAudio) else {

        return
    }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            print("AVAudioSession is Active")
            playerItem = AVPlayerItem(url: url)
            player = AVPlayer(playerItem: playerItem)

            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.slidetOutlet.value = Float ( time )
                    self.slidetOutlet.minimumValue = 0

                    let duration : CMTime = self.playerItem!.asset.duration
                    let seconds : Float64 = CMTimeGetSeconds(duration)

                    self.slidetOutlet.maximumValue = Float(seconds)
                    self.lblStartTimePlayer.text = self.secondsToHoursMinutesSeconds(seconds: seconds)

                    self.lblPlayerTime.text = self.secondsToHoursMinutesSeconds(seconds: Double( self.slidetOutlet.value ))

                }
            }

        } catch let error as NSError {
            print(error.localizedDescription)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

and for convert the time :

func secondsToHoursMinutesSeconds (seconds : Double) -> (String) {
    let (hr,  minf) = modf (seconds / 3600)
    let (min, secf) = modf (60 * minf)
    return ("\(Int(hr)):\(Int(min)):\(Int(60 * secf))")
}

Upvotes: 0

Fahim
Fahim

Reputation: 3556

The player's current time will not automatically update. Instead, you have to periodically update the current time using a timer. Take a look at the following thread if you want more details.

check avaudioplayer's current playback time

Upvotes: 1

Related Questions