Siva Moorthy Siva Moorthy - 9 months ago 52
Swift Question

Audio to video Convert in swift

I managed it to download a audio using NSUrlConnection and save it to the device. Now I want to convert this (I guess .mp3) file to an .mp4 video file.


i Got the solution

    let soundFileUrl = audioURL
    let recordAsset: AVURLAsset = AVURLAsset(URL: soundFileUrl, options: nil)

    let mixComposition: AVMutableComposition = AVMutableComposition()
    let recordTrack: AVMutableCompositionTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

    let tracks1 =  recordAsset.tracksWithMediaType(AVMediaTypeAudio)
    let assetTrack1:AVAssetTrack = tracks1[0]

    let audioDuration:CMTime = assetTrack1.timeRange.duration
        try recordTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioDuration), ofTrack: assetTrack1, atTime: kCMTimeZero)

    } catch {

    let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough)!
    assetExport.outputFileType = AVFileTypeQuickTimeMovie
    assetExport.outputURL = savePathUrl
    assetExport.shouldOptimizeForNetworkUse = true

    assetExport.exportAsynchronouslyWithCompletionHandler( {

        switch assetExport.status {
        case  AVAssetExportSessionStatus.Failed:
            print("failed \(assetExport.error)")
        case AVAssetExportSessionStatus.Cancelled:
            print("cancelled \(assetExport.error)")