I want to use AVPlayer to play audio files on iphone. The audio file is mp3 file from the local storage on device. I need to synchronize it (the played file) with external time source. This time source can change during playing so synchronization is needed from time to time. I used the following code to change the time in the played audio file:
player.play()
//sth here......
//the code which is executed periodically whene it is time to synchronize
let currentShowTime = ...... //time in miliseconds
print("current show time \(currentShowTime)")
let timescale = player.currentItem!.asset.duration.timescale
let currentTime = CMTime(value:Int64(Float64(currentShowTime!) * Float64(timescale) / 1000.0), timescale:timescale)
//alternative way I count the seek time but the effect is the same
//let currentTime = CMTimeMakeWithSeconds(Float64(currentShowTime!)/1000.0, 1000)
print("currenttime \(currentTime)")
player!.seek(to: currentTime,toleranceBefore:kCMTimeZero, toleranceAfter:kCMTimeZero ){done in
print("done: \(done)")
print("player currenttime \(self.player!.currentItem!.currentTime().seconds)")
}
The problem is that the audio file is playing the wrong place. All parameters: current show time, current time and player currenttime are the same (print the same values). But I hear that the sound is shifted. When the beginning of the file is played, the shift is small (maybe 500 ms), but when it comes to the end (the 20 minute of the file) the shift is much greater (about 8 seconds). I also noticed that when I provide smaller mp3 file (with less bit rate) the shift is smaller but when the file is in better quality the shift is up to 20 seconds. Am I doing sth wrong or is it a bug in AVPlayer?