fix: 音视频同步——音频从 firstFrameTime 开始读取

之前音频用 player.currentTime() 作为起始时间,视频用
AVPlayerItemVideoOutput 的 firstFrameTime,两者可能不一致
导致音视频不同步。

改为:
- prepareAudioCapture: 只预加载音频轨道,不立即开始读取
- captureVideoFrame: 第一帧时设置 firstFrameTime 后调用
  beginAudioReading(startTime: firstFrameTime)
- 音频和视频共用同一个时间基准,确保精确同步
- 移除 startRecording 的 startTime 参数
This commit is contained in:
yumoqing 2026-06-24 21:07:07 +08:00
parent 60a3369d82
commit 42f3cf2b84
2 changed files with 69 additions and 37 deletions

View File

@ -122,8 +122,7 @@ final class PlayerBridge: ObservableObject {
}
guard !queue.isEmpty else { return }
let sourceURL = queue[currentIndex].url
let startTime = player.currentTime()
screenRecorder.startRecording(from: output, sourceURL: sourceURL, startTime: startTime)
screenRecorder.startRecording(from: output, sourceURL: sourceURL)
}
#endif
}

View File

@ -22,6 +22,10 @@ final class PlayerRecorder: NSObject {
/// 线 firstFrameTime
nonisolated(unsafe) private var audioFirstFrameTime: CMTime?
//
private var pendingAudioAsset: AVURLAsset?
private var pendingAudioTrack: AVAssetTrack?
@Published var isRecording = false
@Published var durationText = "00:00"
@ -38,7 +42,7 @@ final class PlayerRecorder: NSObject {
}
///
func startRecording(from output: AVPlayerItemVideoOutput, sourceURL: URL, startTime: CMTime) {
func startRecording(from output: AVPlayerItemVideoOutput, sourceURL: URL) {
guard !isRecording else { return }
weakOutput = output
@ -97,8 +101,8 @@ final class PlayerRecorder: NSObject {
startTimer()
startCaptureLoop()
// URL
startAudioCapture(sourceURL: sourceURL, startTime: startTime, audioWriterInput: aInput)
// firstFrameTime
prepareAudioCapture(sourceURL: sourceURL)
}
///
@ -151,6 +155,8 @@ final class PlayerRecorder: NSObject {
audioFirstFrameTime = itemTime // 线
writer?.startSession(atSourceTime: itemTime)
isRunning = true
// firstFrameTime
beginAudioReading(startTime: itemTime)
}
//
@ -182,8 +188,12 @@ final class PlayerRecorder: NSObject {
}
// MARK: - URL
private func startAudioCapture(sourceURL: URL, startTime: CMTime, audioWriterInput: AVAssetWriterInput) {
///
private func prepareAudioCapture(sourceURL: URL) {
let asset = AVURLAsset(url: sourceURL)
pendingAudioAsset = asset
pendingAudioTrack = nil
Task {
do {
@ -192,43 +202,66 @@ final class PlayerRecorder: NSObject {
print("[Recorder] No audio track in source")
return
}
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: [
AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsNonInterleaved: false
])
output.alwaysCopiesSampleData = false
//
reader.timeRange = CMTimeRange(start: startTime, duration: .positiveInfinity)
if reader.canAdd(output) {
reader.add(output)
reader.startReading()
self.audioReader = reader
self.audioReaderOutput = output
// 线
let queue = DispatchQueue(label: "recorder.audio.capture")
self.audioCaptureQueue = queue
queue.async { [weak self] in
guard let self = self, let aInput = self.audioInput else { return }
self.readAudioLoop(reader: reader, output: output, audioInput: aInput)
}
self.pendingAudioTrack = audioTrack
// firstFrameTime
if let fft = self.firstFrameTime {
self.beginAudioReading(startTime: fft)
}
} catch {
print("[Recorder] Audio capture setup failed: \(error)")
print("[Recorder] Audio track load failed: \(error)")
}
}
}
/// firstFrameTime reader
private func beginAudioReading(startTime: CMTime) {
guard let asset = pendingAudioAsset, let audioTrack = pendingAudioTrack else {
return // prepareAudioCapture
}
guard let aInput = audioInput else { return }
//
guard audioReader == nil else { return }
do {
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: [
AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsNonInterleaved: false
])
output.alwaysCopiesSampleData = false
//
reader.timeRange = CMTimeRange(start: startTime, duration: .positiveInfinity)
if reader.canAdd(output) {
reader.add(output)
reader.startReading()
self.audioReader = reader
self.audioReaderOutput = output
// 线
let queue = DispatchQueue(label: "recorder.audio.capture")
self.audioCaptureQueue = queue
queue.async { [weak self] in
guard let self = self else { return }
self.readAudioLoop(reader: reader, output: output, audioInput: aInput)
}
}
} catch {
print("[Recorder] Audio capture setup failed: \(error)")
}
//
pendingAudioAsset = nil
pendingAudioTrack = nil
}
private nonisolated func readAudioLoop(reader: AVAssetReader, output: AVAssetReaderTrackOutput, audioInput: AVAssetWriterInput) {
while !audioStopped && reader.status == .reading {
guard let sampleBuffer = output.copyNextSampleBuffer() else {