Skip to content

Instantly share code, notes, and snippets.

@yycking
Last active December 28, 2023 08:09
Show Gist options
  • Save yycking/44dc9baa5d6e42a55e8e0bc3aa9fcbc8 to your computer and use it in GitHub Desktop.
Save yycking/44dc9baa5d6e42a55e8e0bc3aa9fcbc8 to your computer and use it in GitHub Desktop.
read/write audio file
let musicURL = try! FileManager.default.url(for: .musicDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let source = musicURL.appendingPathComponent("錄音/原始.wav")
let input = try! AVAudioFile(forReading: source)
let format = input.fileFormat
let destination = musicURL.appendingPathComponent("錄音/複製.wav")
let output = try! AVAudioFile(forWriting: destination, settings: format.settings, commonFormat: format.commonFormat, interleaved: format.isInterleaved)
while input.framePosition < input.length {
let capacity = min(input.length - input.framePosition, 1024)
var buffer = AVAudioPCMBuffer(pcmFormat: input.fileFormat, frameCapacity: AVAudioFrameCount(capacity))!
try! input.read(into: buffer)
var data = [Float](repeating: 0, count: Int(capacity))
data.withUnsafeMutableBufferPointer{
let p = buffer.floatChannelData!.pointee
$0.baseAddress?.initialize(from: p, count: Int(capacity))
}
buffer = AVAudioPCMBuffer(pcmFormat: output.fileFormat, frameCapacity: UInt32(capacity))!
buffer.floatChannelData?.pointee.update(from: data, count: Int(capacity))
buffer.frameLength = AVAudioFrameCount(capacity)
try! output.write(from: buffer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment