Skip to content

Instantly share code, notes, and snippets.

@AkiyukiOkayasu
Last active October 15, 2022 09:59
Show Gist options
  • Save AkiyukiOkayasu/e225de8789f156620b5e4a52db6f8662 to your computer and use it in GitHub Desktop.
Save AkiyukiOkayasu/e225de8789f156620b5e4a52db6f8662 to your computer and use it in GitHub Desktop.
Minimal wav file read and write in Go lang
package main
import (
"os"
"github.com/go-audio/wav"
)
const filename = "pulse440_32bitFloat48kHz.wav"
//const filename = "pulse440_16bit48kHz.wav"
//const filename = "pulse440_24bit48kHz.wav"
func main() {
// Open Wav file
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
// Create wav decoder
wd := wav.NewDecoder(f)
if wd.IsValidFile() {
// Get IntBuffer
buf, err := wd.FullPCMBuffer()
if err != nil {
panic(err)
}
// Create output wav file
out, err := os.Create("output.wav")
if err != nil {
panic(err)
}
defer out.Close()
// Create wav encoder
e := wav.NewEncoder(out,
buf.Format.SampleRate,
int(wd.BitDepth),
buf.Format.NumChannels,
int(wd.WavAudioFormat))
defer e.Close()
// Write IntBuffer to output file via encoder
if err = e.Write(buf); err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment