From b45c38119f96bd5cfa7b19df1e20d07ad2950a9a Mon Sep 17 00:00:00 2001 From: Doug Date: Tue, 11 Feb 2020 12:29:15 +0000 Subject: [PATCH] Fix waveform rendering for some assets derived from video files. --- .../FDWaveformRenderOperation.swift | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/FDWaveformView/FDWaveformRenderOperation.swift b/FDWaveformView/FDWaveformRenderOperation.swift index f880848..687b549 100755 --- a/FDWaveformView/FDWaveformRenderOperation.swift +++ b/FDWaveformView/FDWaveformRenderOperation.swift @@ -150,8 +150,17 @@ final public class FDWaveformRenderOperation: Operation { let reader = try? AVAssetReader(asset: audioContext.asset) else { return nil } - reader.timeRange = CMTimeRange(start: CMTime(value: Int64(slice.lowerBound), timescale: audioContext.asset.duration.timescale), - duration: CMTime(value: Int64(slice.count), timescale: audioContext.asset.duration.timescale)) + var channelCount = 1 + var sampleRate: CMTimeScale = 44100 + let formatDescriptions = audioContext.assetTrack.formatDescriptions as! [CMAudioFormatDescription] + for item in formatDescriptions { + guard let fmtDesc = CMAudioFormatDescriptionGetStreamBasicDescription(item) else { return nil } + channelCount = Int(fmtDesc.pointee.mChannelsPerFrame) + sampleRate = Int32(fmtDesc.pointee.mSampleRate) + } + + reader.timeRange = CMTimeRange(start: CMTime(value: Int64(slice.lowerBound), timescale: sampleRate), + duration: CMTime(value: Int64(slice.count), timescale: sampleRate)) let outputSettingsDict: [String : Any] = [ AVFormatIDKey: Int(kAudioFormatLinearPCM), AVLinearPCMBitDepthKey: 32, @@ -164,13 +173,6 @@ final public class FDWaveformRenderOperation: Operation { readerOutput.alwaysCopiesSampleData = false reader.add(readerOutput) - var channelCount = 1 - let formatDescriptions = audioContext.assetTrack.formatDescriptions as! [CMAudioFormatDescription] - for item in formatDescriptions { - guard let fmtDesc = CMAudioFormatDescriptionGetStreamBasicDescription(item) else { return nil } - channelCount = Int(fmtDesc.pointee.mChannelsPerFrame) - } - let samplesPerPixel = max(1, channelCount * slice.count / targetSamples) var outputSamples = [WaveformSample]()