Skip to content

Instantly share code, notes, and snippets.

@moutend
Created March 13, 2021 00:54
Show Gist options
  • Save moutend/4bebd485967f4c11cc4fe8e6a2185121 to your computer and use it in GitHub Desktop.
Save moutend/4bebd485967f4c11cc4fe8e6a2185121 to your computer and use it in GitHub Desktop.
SwiftでWAV形式の音声ファイルをInt16の配列として読み込む
import AVFoundation
func readWavFile(_ path: String) -> [[Int16]]? {
guard let url = URL(string: path) else {
return nil
}
guard let audio = try? AVAudioFile(forReading: url, commonFormat: .pcmFormatInt16, interleaved: false) else {
return nil
}
guard let buffer = AVAudioPCMBuffer(pcmFormat: audio.processingFormat, frameCapacity: AVAudioFrameCount(audio.length)) else {
return nil
}
do {
try audio.read(into: buffer)
} catch {
return nil
}
guard let int16ChannelData = buffer.int16ChannelData else {
return nil
}
var channelData = [[Int16]]()
for i in 0 ..< Int(audio.processingFormat.channelCount) {
channelData.append(Array(UnsafeBufferPointer(start: int16ChannelData[i], count: Int(buffer.frameLength))))
}
return channelData
}
func printSignal(_ path: String) {
guard let signal = readWavFile(path) else {
return
}
if signal.count < 2 {
return
}
print("Left\tRight")
for i in 0 ..< signal[0].count {
print(String(format: "%d\t%d", signal[0][i], signal[1][i]))
}
}
printSignal("/tmp/music.wav")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment