ios 使用AVFoundation从视频中提取音频
在导出音频文件时候,使用 m4a格式或者wav格式,总会遇到某些视频无法正常导出,使用caf(core audio format)则可以正常导出。如果需要其他格式的音频,可以导出caf之后进行转码。
extension AVAsset {
func writeAudioTrack(to url: URL,
success: @escaping () -> (),
failure: @escaping (Error) -> ()) {
do {
let asset = try audioAsset()
asset.write(to: url, success: success, failure: failure)
} catch {
failure(error)
}
}
private func write(to url: URL,
success: @escaping () -> (),
failure: @escaping (Error) -> ()) {
try? FileManager().removeItem(at: url)
// Create an export session that will output an
// audio track (CAF file)
guard let exportSession = AVAssetExportSession(asset: self,
presetName: AVAssetExportPresetPassthrough) else {
// This is just a generic error
let error = NSError(domain: "domain",
code: 0,
userInfo: nil)
failure(error)
return
}
exportSession.outputFileType = .caf
exportSession.outputURL = url
exportSession.exportAsynchronously {
switch exportSession.status {
case .completed:
success()
default:
let error = NSError(domain: "domain", code: 0, userInfo: nil)
failure(error)
break
}
}
}
private func audioAsset() throws -> AVAsset {
let composition = AVMutableComposition()
let audioTracks = tracks(withMediaType: .audio)
for track in audioTracks {
let compositionTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
try compositionTrack?.insertTimeRange(track.timeRange, of: track, at: track.timeRange.start)
compositionTrack?.preferredTransform = track.preferredTransform
}
return composition
}
}
网友评论