Ziad Halabi
Ziad Halabi

Reputation: 866

Swift - How to get the current position of AVAudioPlayerNode while it's looping?

I have an AVAudioPlayerNode looping a segment of a song:

audioPlayer.scheduleBuffer(segment, at: nil, options:.loops)

I want to get current position of the song while it's playing. Usually, this is done by calculating = currentFrame / audioSampleRate

where

var currentFrame: AVAudioFramePosition {
        
        guard let lastRenderTime = audioPlayer.lastRenderTime,
            
            let playerTime = audioPlayer.playerTime(forNodeTime: lastRenderTime) else {
                return 0
        }
        return playerTime.sampleTime
    }

However, when the loop ends and restarts, the currentFrame does not restart. But it still increases which makes currentFrame / audioSampleRate incorrect as the current position.

So what is the correct way to calculate the current position?

Upvotes: 1

Views: 691

Answers (1)

Eric
Eric

Reputation: 16931

Good old modulo will do the job:

public var currentTime: TimeInterval {
    guard let nodeTime = player.lastRenderTime,
        let playerTime = player.playerTime(forNodeTime: nodeTime) else {
            return 0
    }
    let time = (Double(playerTime.sampleTime) / playerTime.sampleRate)
        .truncatingRemainder(dividingBy: Double(file.length) / Double(playerTime.sampleRate))
    return time
}

Upvotes: 2

Related Questions