【问题标题】:Silence is not adding on end of an audio file静音不会添加到音频文件的末尾
【发布时间】:2020-05-23 14:35:48
【问题描述】:

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

我的音频文件长度为 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】:

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

    所以……

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

    改成类似

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

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

    【讨论】:

    • 感谢@Scriptable 的回复。我已经尝试过上面的逻辑,但不幸的是上面的逻辑不起作用,它仍然给我同样的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多