美文网首页
ios 使用AVFoundation从视频中提取音频

ios 使用AVFoundation从视频中提取音频

作者: 刘乔泓 | 来源:发表于2020-12-08 21:07 被阅读0次

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
    }
}

相关文章

网友评论

      本文标题:ios 使用AVFoundation从视频中提取音频

      本文链接:https://www.haomeiwen.com/subject/lxgqgktx.html