|
| 1 | +// |
| 2 | +// Copyright 2013 - 2017, William Entriken and the FDWaveformView contributors. |
| 3 | +// |
| 4 | +import UIKit |
| 5 | +import AVFoundation |
| 6 | + |
| 7 | +/// Holds audio information used for building waveforms |
| 8 | +final class FDAudioContext { |
| 9 | + |
| 10 | + /// The audio asset URL used to load the context |
| 11 | + public let audioURL: URL |
| 12 | + |
| 13 | + /// Total number of samples in loaded asset |
| 14 | + public let totalSamples: Int |
| 15 | + |
| 16 | + /// Loaded asset |
| 17 | + public let asset: AVAsset |
| 18 | + |
| 19 | + // Loaded assetTrack |
| 20 | + public let assetTrack: AVAssetTrack |
| 21 | + |
| 22 | + private init(audioURL: URL, totalSamples: Int, asset: AVAsset, assetTrack: AVAssetTrack) { |
| 23 | + self.audioURL = audioURL |
| 24 | + self.totalSamples = totalSamples |
| 25 | + self.asset = asset |
| 26 | + self.assetTrack = assetTrack |
| 27 | + } |
| 28 | + |
| 29 | + public static func load(fromAudioURL audioURL: URL, completionHandler: @escaping (_ audioContext: FDAudioContext?) -> ()) { |
| 30 | + let asset = AVURLAsset(url: audioURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: NSNumber(value: true as Bool)]) |
| 31 | + |
| 32 | + guard let assetTrack = asset.tracks(withMediaType: AVMediaTypeAudio).first else { |
| 33 | + NSLog("FDWaveformView failed to load AVAssetTrack") |
| 34 | + completionHandler(nil) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + asset.loadValuesAsynchronously(forKeys: ["duration"]) { |
| 39 | + var error: NSError? |
| 40 | + let status = asset.statusOfValue(forKey: "duration", error: &error) |
| 41 | + switch status { |
| 42 | + case .loaded: |
| 43 | + guard |
| 44 | + let audioFormatDesc = assetTrack.formatDescriptions.first, |
| 45 | + let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(audioFormatDesc as! CMAudioFormatDescription) // TODO: Can this be safer? |
| 46 | + else { break } |
| 47 | + |
| 48 | + let totalSamples = Int((asbd.pointee.mSampleRate) * Float64(asset.duration.value) / Float64(asset.duration.timescale)) |
| 49 | + let audioContext = FDAudioContext(audioURL: audioURL, totalSamples: totalSamples, asset: asset, assetTrack: assetTrack) |
| 50 | + completionHandler(audioContext) |
| 51 | + return |
| 52 | + |
| 53 | + case .failed, .cancelled, .loading, .unknown: |
| 54 | + print("FDWaveformView could not load asset: \(error?.localizedDescription ?? "Unknown error")") |
| 55 | + } |
| 56 | + |
| 57 | + completionHandler(nil) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments