ios音訊處理 音軌合成 swift
話不多少,直接上程式碼,程式碼中講解使用注意
下文音訊檔案拼接,音軌合成統稱為合成
let composition:AVMutableComposition =AVMutableComposition() //想要合成音訊檔案,第一步,必須建立AVMutableComposition,類似於很多api這個字尾也為composition,意思可以理解為合成物,但不是最終產生的檔案
let appendedAudioTrack:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio
//此處建立的為音軌屬性,可以理解為合成物所需要的原料 ,對音軌的加工都在這個方法裡面進行,此處為音訊合成MediaType為 AVMediaTypeAudio
let url =getAudioUrl()
//本地音訊檔案的url
let originalAsset:AVURLAsset =AVURLAsset(URL: url, options:nil)
//將原始檔轉換為可處理的資源(初始資產),可理解為初次加工
let assetTrack1 = originalAsset.
//將初始資產再加工生成可用於拼接的(音軌資產) tracksWithMediaType()輸出為[AVAssetTrack]陣列取處於第一位的資源,也可能產物就是一個,只不過相當於用了個筐來盛放
let timeRange1 =CMTimeRangeMake(kCMTimeZero, originalAsset.duration)
//控制時間範圍
try! appendedAudioTrack.insertTimeRange(timeRange1, ofTrack: assetTrack1, atTime:
//最終將可 拼接的音軌資源插入到空白的原料池裡面 值得注意的是insertTimeRange(timeRange1, ofTrack: assetTrack1, atTime: kCMTimeZero)
以上的過程也只是音軌合成的第一步(只要選好插入的時間點,插入的音軌資源可將多個assetTrack1(音軌資產)拼接到一起,即為音訊資源的拼接),接著向下看let anotherAudioTrack:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
for seninlistSentences{
let path =getRealPath(["record",getCurrentUser().id,"\(currentMovie.name)","\(sen.sentenceIdx - 1).mp3"])
print(path)
let url:NSURL =NSURL(fileURLWithPath: path)
let newAsset:AVURLAsset =AVURLAsset(URL: url, options:nil)
let assetTrack2 = newAsset.tracksWithMediaType(AVMediaTypeAudio)[0]
let timeRange2 =CMTimeRangeMake(kCMTimeZero, newAsset.duration)
let beginTime =CMTime(seconds:Double(sen.timeStartMS)/1000, preferredTimescale:100)
print(Double(sen.timeStartMS)/1000)
try! anotherAudioTrack.insertTimeRange(timeRange2, ofTrack: assetTrack2, atTime: beginTime)
}
上面將不同的片段拼接到一起,生成了anotherAudioTrack,其與最上面的appendedAudioTrack同為composition的原料此時可將這兩個原料進行合成即為音軌的合成,最後生成的聲音檔案聲音相互重疊,如電影中聽到的人聲與背景音 如果不需要兩個音軌的合成只需要拼接 ,此時只需要建立一個AVMutableCompositionTrack物件,最上面的添加註釋的程式碼就不需要了下面重點來了,要生成檔案必須要用到它
let exportSession:AVAssetExportSession =AVAssetExportSession(asset: composition, presetName:AVAssetExportPresetAppleM4A)!
//這裡就用到了上面的composition,composition作為原料加上下面的各種屬性最終生成了指定路徑下的目標檔案
if exportSession ==false {
// do something
return
}
let realPath =getRealPath(["record",getCurrentUser().id,currentMovie.name,"total.m4a"]) //指定路徑
// make sure to fill this value in
exportSession.outputURL =NSURL(fileURLWithPath: realPath)
exportSession.outputFileType =AVFileTypeAppleM4A
exportSession.exportAsynchronouslyWithCompletionHandler({() ->Voidin
// exported successfully?
print("exportSession...",exportSession)
switch exportSession.status {
case .Failed:
break
case .Completed:
// you should now have the appended audio file
break
case .Waiting:break
default:break
}
// var error: NSErrorPointer? = nil
})
這裡最終生成的檔案為m4a格式
AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)!中的presetName必須與exportSession.outputFileType中的outputFileType相對應,否則就會crash或生成的檔案全是噪雜聲