未在音频文件末尾添加静音

问题描述 投票:0回答:1

我正在演示如何在给定音频文件的末尾添加额外的静音音频的演示。

这里我的音频文件长度为29秒。 &我添加了11秒的静音。因此,最终的输出音频长度将为40秒。

这是我的职能

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)
            }
        })
    }

以上代码成功运行,并且我的音频输出在40秒内。

但是在音频文件的开头添加了11秒的静音问题。

它应该在音频文件的末尾。

我在这里做错什么了?

ios swift avassetexportsession avmutablecomposition avurlasset
1个回答
0
投票

您基本上只需要延长音频的长度。

所以...

let assetTimeRange = CMTimeRange(start: CMTime.zero, end:asset.duration)

更改为类似内容>>

let newDuration = asset.duration + silenceTime
let assetTimeRange = CMTimeRange(start: CMTime.zero, end:newDuration)

免责声明:自从我这样做已经有一段时间了

© www.soinside.com 2019 - 2024. All rights reserved.