Reputation: 1283
I'm working on a demo of how to add extra silence audio at the end of a given audio file.
here my audio file length is 29 sec. & I'm adding 11-sec silence. so, final output audio length will be 40 sec.
Here is my function,
func addSilenceInAudio(inputFilePath:URL, silenceTime: Int, minimumAudioLength: Int, completionBlock:@escaping ((String?, Error?) -> Void)) {
let asset = AVURLAsset(url: inputFilePath, options: nil)
//get an original audio length
let endAudioTime = CMTimeMake(value: Int64(silenceTime), timescale: 1)
let composition = AVMutableComposition()
let insertAt = CMTimeRange(start: CMTime.zero , end: endAudioTime)
let assetTimeRange = CMTimeRange(start: CMTime.zero, end:asset.duration)
//here i'm inserting range
try! composition.insertTimeRange(assetTimeRange, of: asset, at: insertAt.end)
let exportSessionNew = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
exportSessionNew?.outputFileType = AVFileType.m4a
let documentURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let dateString = (Date().millisecondsSince1970) //added file name here
let outputURL = documentURL.appendingPathComponent("\(dateString).m4a") //file name must be .m4a
exportSessionNew?.outputURL = outputURL //output url
exportSessionNew?.exportAsynchronously(completionHandler: {
() -> Void in
print(exportSessionNew as Any)
if exportSessionNew!.status == AVAssetExportSession.Status.completed {
// All is working fine!!
print(exportSessionNew?.outputURL as Any) //get outputfile
print("success")
completionBlock("\(String(describing: exportSessionNew?.outputURL))", nil)
} else {
print("failed")
completionBlock(nil, exportSessionNew?.error)
}
})
}
above code is working fine & I'm getting my output audio with 40 sec.
but the Problem is 11-sec silence is adding in starting of an audio file.
it should be at the end of an audio file.
I'm doing something wrong here?
Upvotes: 2
Views: 438
Reputation: 19758
You basically only need to extend the length of the audio.
So...
let assetTimeRange = CMTimeRange(start: CMTime.zero, end:asset.duration)
change to something like
let newDuration = asset.duration + silenceTime
let assetTimeRange = CMTimeRange(start: CMTime.zero, end:newDuration)
Disclaimer: It's a while since I've done this
Upvotes: 0