Created
July 28, 2021 01:19
-
-
Save standinga/c04f8a39425f4a0b0d39580ac5618390 to your computer and use it in GitHub Desktop.
Reverse audio file in Swift using Accelerate framework (this is fast)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Accelerate | |
import AVFoundation | |
func reverse(fromUrl: URL) -> URL? { | |
do { | |
let input = try AVAudioFile(forReading: fromUrl) | |
let format = input.processingFormat | |
let frameCount = AVAudioFrameCount(input.length) | |
let outSettings = [AVNumberOfChannelsKey: format.channelCount, | |
AVSampleRateKey: format.sampleRate, | |
AVLinearPCMBitDepthKey: 16, | |
AVFormatIDKey: kAudioFormatMPEG4AAC] as [String: Any] | |
let outputUrl = FileManager.default.temporaryDirectory.appendingPathComponent("reversed.m4a") | |
try? FileManager.default.removeItem(at: outputUrl) | |
let output = try AVAudioFile(forWriting: outputUrl, settings: outSettings) | |
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount) else { | |
return nil | |
} | |
try input.read(into: buffer) | |
let frameLength = buffer.frameLength | |
guard let data = buffer.floatChannelData else { return nil } | |
for i in 0..<buffer.format.channelCount { | |
let stride = vDSP_Stride(1) | |
vDSP_vrvrs(data.advanced(by: Int(i)).pointee, stride, vDSP_Length(frameLength)) | |
} | |
try output.write(from: buffer) | |
return outputUrl | |
} catch let error { | |
print(error.localizedDescription) | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how do you implement this code any help aprieshiated