我正在使用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
无法转换为wav?如果AVAssetExportSession
不适合此作业,AVAssetReader / AVAssetWriter或扩展音频文件服务是否可以使用?谢谢你的阅读。
答案 0 :(得分:0)
是的,据我了解,您需要为此使用CoreAudio。在此类中查看函数convertToPCM:
https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Internals/AKConverter.swift