0

我有一个AVAudioPlayerNode循环的歌曲片段:

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

我想在播放时获取歌曲的当前位置。通常,这是通过计算 =currentFrame / audioSampleRate

在哪里

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

但是,当循环结束并重新启动时,currentFrame不会重新启动。但它仍然会增加,这使得currentFrame / audioSampleRate当前位置不正确。

那么计算当前位置的正确方法是什么?

4

1 回答 1

1

好的旧模数可以完成这项工作:

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
}
于 2021-02-15T13:18:49.377 回答