Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display song currenttime and duration by using AVAudioPlayerNode

I'm making an audio player using AVAudioPlayerNode and playing a song with some effect (delay, pitch change, rate change etc) works, but I'm stuck on displaying song current time and duration. AVAudioPlayerNode seems not have like AVAudioPlayer.currentTime or .duration.

I'd really appreciate if you can help me to display currenttime and duration by using AVAudioPlayerNode.

like image 259
Bick Avatar asked Oct 26 '14 15:10

Bick


2 Answers

For the current time, this is what I use:

- (NSTimeInterval)currentTimeInSeconds
{
    AVAudioTime *nodeTime = self.playerNode.lastRenderTime;
    AVAudioTime *playerTime = [self.playerNode playerTimeForNodeTime:nodeTime];

    NSTimeInterval seconds = (double)playerTime.sampleTime / playerTime.sampleRate; 
    return seconds;
}

In addition to the render time in an abstract time base, the player node offers conversion of this time into its own playback timeline via playerTimeForNodeTime. Also respects pausing etc.

like image 127
Thorsten Karrer Avatar answered Jan 03 '23 22:01

Thorsten Karrer


Here it is in swift:

private func currentTime() -> NSTimeInterval {
    if let nodeTime: AVAudioTime = myAvAudioPlayer.lastRenderTime, playerTime: AVAudioTime = myAvAudioPlayer.playerTimeForNodeTime(nodeTime) {
       return Double(Double(playerTime.sampleTime) / playerTime.sampleRate)
    }
    return 0
}

Just replace myAvAudioPlayer with your AVAudioPlayerNode!

Happy coding!

like image 33
Tomte Avatar answered Jan 04 '23 00:01

Tomte