怎么在不使用FFmpeg的情况下提取视频文件中的音频?
我想使用AVMutableComposition
和AVURLAsset
来解决这个问题,例如将.mov文件转换为.m4a文件。
怎么在不使用FFmpeg的情况下提取视频文件中的音频?
我想使用AVMutableComposition
和AVURLAsset
来解决这个问题,例如将.mov文件转换为.m4a文件。
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)
}
}
}
}
TRAK>MDIA>MINF>STBL
内部的STCO
表(或CO64
)中。每个块的长度是另一个需要根据STBL
中的信息计算的值。请参阅此参考资料。 - onon15
.flv
”文件一无所知,因此这个问题根本就行不通。这就是为什么你需要使用一些第三方库,比如ffmpeg或其他类似的库,来打开.flv文件并将其转换为你可以正确使用的格式。 - Michael Dautermann