Last active
December 28, 2023 08:09
-
-
Save yycking/44dc9baa5d6e42a55e8e0bc3aa9fcbc8 to your computer and use it in GitHub Desktop.
read/write audio file
This file contains 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
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