Skip to content

Instantly share code, notes, and snippets.

@standinga
Created July 28, 2021 01:19
Show Gist options
  • Select an option

  • Save standinga/c04f8a39425f4a0b0d39580ac5618390 to your computer and use it in GitHub Desktop.

Select an option

Save standinga/c04f8a39425f4a0b0d39580ac5618390 to your computer and use it in GitHub Desktop.
Reverse audio file in Swift using Accelerate framework (this is fast)
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
}
}
@soundmagic2009
Copy link
Copy Markdown

how do you implement this code any help aprieshiated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment