iOS Audio Trimming

前端 未结 4 1922
既然无缘
既然无缘 2020-11-28 05:08

I searched a lot and couldn\'t find anything relevant... I am working on iOS audio files and here is what I want to do...

  1. Record Audio and Save Clip (Checked,
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:41

    // Swift 4.2

    If anybody is still looking for answer in swift here it is.

    //Audio Trimming

    func trimAudio(asset: AVAsset, startTime: Double, stopTime: Double, finished:@escaping (URL) -> ())
    {
    
            let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith:asset)
    
            if compatiblePresets.contains(AVAssetExportPresetMediumQuality) {
    
            guard let exportSession = AVAssetExportSession(asset: asset, 
            presetName: AVAssetExportPresetAppleM4A) else{return}
    
            // Creating new output File url and removing it if already exists.
            let furl = createUrlInAppDD("trimmedAudio.m4a") //Custom Function
            removeFileIfExists(fileURL: furl) //Custom Function
    
            exportSession.outputURL = furl
            exportSession.outputFileType = AVFileType.m4a
    
            let start: CMTime = CMTimeMakeWithSeconds(startTime, preferredTimescale: asset.duration.timescale)
            let stop: CMTime = CMTimeMakeWithSeconds(stopTime, preferredTimescale: asset.duration.timescale)
            let range: CMTimeRange = CMTimeRangeFromTimeToTime(start: start, end: stop)
            exportSession.timeRange = range
    
            exportSession.exportAsynchronously(completionHandler: {
    
                switch exportSession.status {
                case .failed:
                    print("Export failed: \(exportSession.error!.localizedDescription)")
                case .cancelled:
                    print("Export canceled")
                default:
                    print("Successfully trimmed audio")
                    DispatchQueue.main.async(execute: {
                        finished(furl)
                    })
                }
            })
        }
    }
    

    You can use it for video trimming as well. For Video trimming replace the value of export session as bellow:

    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else{return}

    and filetype to mp4

    exportSession.outputFileType = AVFileType.mp4

提交回复
热议问题