HomeiOS Developmentios - Find out how to correctly convert a .m4a file into...

ios – Find out how to correctly convert a .m4a file into .caf file in swift


I’ve an audio file with .m4a extension I would like it to be transformed into .caf file. I’ve a operate prepared and dealing. It really works advantageous however when enhancing the audio by way of code (altering the velocity, pitch, echo and reverb) it returns an eroor stating:

“failed Non-obligatory(Error Area=AVFoundationErrorDomain Code=-11800 “The operation couldn’t be accomplished” UserInfo={NSLocalizedFailureReason=An unknown error occurred (-12780), NSLocalizedDescription=The operation couldn’t be accomplished, NSUnderlyingError=0x600001878a80 {Error Area=NSOSStatusErrorDomain Code=-12780 “(null)”}})”

The operate used for the conversion is:

func convertAudioFileToCaf(inputURL: URL, outputURL: URL, completion: @escaping (Bool) -> Void) {
    let asset = AVURLAsset(url: inputURL, choices: nil)
    let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)
    exportSession?.outputURL = outputURL
exportSession?.outputFileType = AVFileType.caf
    exportSession?.exportAsynchronously(completionHandler: {
        change exportSession!.standing {
        case .accomplished:
            completion(true)
        case .failed:
            print("failed (String(describing: exportSession?.error))")
            completion(false)
        case .cancelled:
            print("cancelled (String(describing: exportSession?.error))")
            completion(false)
        default:
            break
        }
    })
}

The file is enjoying however when enhancing it there’s an error.
The operate so as to add results:

func play(){
        do {
            guard let url = urlSong else{return}
            let sourceFileURL = url // it's .caf file url of the operate convertAudioFileToCaf.
            sourceFile = attempt AVAudioFile(forReading: sourceFileURL)
            format = sourceFile.processingFormat
        } catch {
            print("Unable to load the supply audio file: (error.localizedDescription).")
        }
        engine.connect(participant)
        engine.connect(reverb)
        engine.connect(playbackRateEffect)
        engine.connect(pitchEffect)
        // Set the specified reverb parameters.
        reverb.loadFactoryPreset(.cathedral)
        reverb.wetDryMix = 50
        playbackRateEffect.price = 2
        engine.connect(playbackRateEffect)
        //Pitch
        pitchEffect.price = 1
        pitchEffect.pitch = -1500
        engine.connect(pitchEffect)
        //Echo
//        echoEffect.delayTime = TimeInterval(60)
//        engine.connect(echoEffect)
        // Join the nodes.
        engine.join(participant, to: playbackRateEffect, format: sourceFile.processingFormat)
        engine.join(playbackRateEffect, to: pitchEffect, format: sourceFile.processingFormat)
//        engine.join(pitchEffect, to: echoEffect, format: sourceFile.processingFormat)
        engine.join(pitchEffect, to: reverb, format: sourceFile.processingFormat)
        engine.join(reverb, to: engine.mainMixerNode, format: sourceFile.processingFormat)
        participant.scheduleFile(sourceFile, at: nil)
        do {
            let maxFrames: AVAudioFrameCount = 4096
            attempt engine.enableManualRenderingMode(.offline, format: format,
                                                 maximumFrameCount: maxFrames)
        } catch {
            print("Enabling handbook rendering mode failed.")
        }
        do {
            attempt engine.begin()
            participant.play()
        } catch {
            fatalError("Unable to begin audio engine: (error).")
        }
        let buffer = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat,
                                      frameCapacity: engine.manualRenderingMaximumFrameCount)!
        do {
            let outputURL = documentsURL.appendingPathComponent("effectedSound(Int(Date().timeIntervalSince1970)).caf")
            outputFile = attempt AVAudioFile(forWriting: outputURL, settings: sourceFile.fileFormat.settings)
            newCafUrl = outputURL
            print(outputURL)
        } catch {
            print("Unable to open output audio file")
        }
        whereas engine.manualRenderingSampleTime < sourceFile.size {
            do {
                let frameCount = sourceFile.size - engine.manualRenderingSampleTime
                let framesToRender = min(AVAudioFrameCount(frameCount), buffer.frameCapacity)
                let standing = attempt engine.renderOffline(framesToRender, to: buffer)
                let ct = buffer.frameCapacity
                if standing == .success{
                    attempt outputFile.write(from: buffer)
                    let dataptrptr = buffer.floatChannelData!
                    let dataptr = dataptrptr.pointee
                    let datum = abs(dataptr[Int(buffer.frameLength)-1])
                    print(datum)
                    if datum < 0.00001 && true {
                        break
                    }
                } else{
                    print("Error whereas writing file")
                }
            } catch {
                fatalError("The handbook rendering failed: (error).")
            }
        }
        let outM4aURL = documentsURL.appendingPathComponent("equalized(Int(Date().timeIntervalSince1970)).m4a")
        convertAudioFileToM4a(inputURL: newCafUrl!, outputURL: outM4aURL) { success in
            print(outM4aURL)
        }
        // Cease the participant node and engine.
        participant.cease()
        engine.cease()
    }

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments