[英]Converting MP4 to WAV with AVAssetExportSession
我正在使用AVAssetExportSession
并希望将音频从MP4视频转换为WAV。 我怀疑使用此工具可能无法实现,但想检查一下是否丢失了任何东西。 这是将其转换为M4A的代码。
func saveAudioFromVideo(withURL url:NSURL){
// Create composition of all audio tracks in asset
print("Creating composition...")
let sourceAsset = AVURLAsset(URL: url)
let sourceTracks = sourceAsset.tracksWithMediaType(AVMediaTypeAudio)
let audioComposition = AVMutableComposition()
for track in sourceTracks{
let compositionTrack = audioComposition.addMutableTrackWithMediaType(AVMediaTypeAudio,
preferredTrackID: kCMPersistentTrackID_Invalid)
do{
try compositionTrack.insertTimeRange(track.timeRange, ofTrack: track, atTime: kCMTimeZero)
}catch{
print("Track insert failed")
}
}
// Get output URL
print("Getting output URL...",terminator:" ")
let documentsPath = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory,
inDomains: .UserDomainMask)[0]
let outputURL = documentsPath.URLByAppendingPathComponent("ConvertedAudio.m4a")
print(outputURL)
// Removing previous instance
print("Checking for previous file...", terminator:" ")
if NSFileManager.defaultManager().fileExistsAtPath(outputURL.path!){
print("found!");
do{
try NSFileManager.defaultManager().removeItemAtURL(outputURL)
print("File removed.")
}catch{
print("Could not remove previous file")
return
}
}
// Setup export session
print("Setting up export session...")
guard let exportSession = AVAssetExportSession(asset: audioComposition,
presetName: AVAssetExportPresetAppleM4A) else{
print("Export session could not be created")
return
}
exportSession.outputFileType = AVFileTypeAppleM4A
exportSession.outputURL = outputURL
// Export data to new format
print("Exporting data...",terminator:" ")
exportSession.exportAsynchronouslyWithCompletionHandler{
let status = exportSession.status
print("complete")
switch status{
case .Completed:
print("Success.")
self.delegate?.audioConverted(withURL: exportSession.outputURL!)
case .Failed:
print("Fail: \(exportSession.error)")
default:
break
}
}
}
这段代码有效,但是将我的outputFileType
更改为AVFileTypeWAVE
,将我的输出文件扩展名更改为.wav,并将会话的预设更改为“ passthrough”给我一个错误:
错误域= AVFoundationErrorDomain代码= -11838“操作已停止” UserInfo = {NSLocalizedDescription =操作已停止,NSLocalizedFailureReason =此媒体不支持该操作。}
知道我哪里出错了吗? 还是使用AVAssetExportSession
无法转换为波形? 如果AVAssetExportSession
不是适合此工作的工具,则使用AVAssetReader / AVAssetWriter或扩展音频文件服务吗? 谢谢阅读。
是的,据我了解,您需要为此使用CoreAudio。 在此类中查看函数convertToPCM:
https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Internals/AKConverter.swift
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.