gpt4 book ai didi

iphone - 从视频文件中提取音频

转载 作者:可可西里 更新时间:2023-11-01 04:42:25 33 4
gpt4 key购买 nike

如何不使用 FFmpeg 从视频文件中提取音频?

我想使用 AVMutableCompositionAVURLAsset 来解决它。例如从 .mov 到 .m4a 文件的转换。

最佳答案

以下 Swift 5/iOS 12.3 代码显示了如何从电影文件 (.mov) 中提取音频并将其转换为音频文件 (.m4a)使用 AVURLAssetAVMutableCompositionAVAssetExportSession:

import UIKit
import AVFoundation

class ViewController: UIViewController {

@IBAction func extractAudioAndExport(_ sender: UIButton) {
// Create a composition
let composition = AVMutableComposition()
do {
let sourceUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov")!
let asset = AVURLAsset(url: sourceUrl)
guard let audioAssetTrack = asset.tracks(withMediaType: AVMediaType.audio).first else { return }
guard let audioCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) else { return }
try audioCompositionTrack.insertTimeRange(audioAssetTrack.timeRange, of: audioAssetTrack, at: CMTime.zero)
} catch {
print(error)
}

// Get url for output
let outputUrl = URL(fileURLWithPath: NSTemporaryDirectory() + "out.m4a")
if FileManager.default.fileExists(atPath: outputUrl.path) {
try? FileManager.default.removeItem(atPath: outputUrl.path)
}

// Create an export session
let exportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough)!
exportSession.outputFileType = AVFileType.m4a
exportSession.outputURL = outputUrl

// Export file
exportSession.exportAsynchronously {
guard case exportSession.status = AVAssetExportSession.Status.completed else { return }

DispatchQueue.main.async {
// Present a UIActivityViewController to share audio file
guard let outputURL = exportSession.outputURL else { return }
let activityViewController = UIActivityViewController(activityItems: [outputURL], applicationActivities: [])
self.present(activityViewController, animated: true, completion: nil)
}
}
}

}

关于iphone - 从视频文件中提取音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11431388/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com