Skip to content

Instantly share code, notes, and snippets.

@dstotijn
Last active August 15, 2024 20:22
Show Gist options
  • Save dstotijn/9741aecb2ecccf4786939cb534a6f49a to your computer and use it in GitHub Desktop.
Save dstotijn/9741aecb2ecccf4786939cb534a6f49a to your computer and use it in GitHub Desktop.
pcm2wav
package main
import (
"encoding/binary"
"io"
"log"
"os"
"github.com/go-audio/audio"
"github.com/go-audio/wav"
)
func main() {
// Read raw PCM data from input file.
in, err := os.Open("audio.pcm")
if err != nil {
log.Fatal(err)
}
// Output file.
out, err := os.Create("output.wav")
if err != nil {
log.Fatal(err)
}
defer out.Close()
// 8 kHz, 16 bit, 1 channel, WAV.
e := wav.NewEncoder(out, 8000, 16, 1, 1)
// Create new audio.IntBuffer.
audioBuf, err := newAudioIntBuffer(in)
if err != nil {
log.Fatal(err)
}
// Write buffer to output file. This writes a RIFF header and the PCM chunks from the audio.IntBuffer.
if err := e.Write(audioBuf); err != nil {
log.Fatal(err)
}
if err := e.Close(); err != nil {
log.Fatal(err)
}
}
func newAudioIntBuffer(r io.Reader) (*audio.IntBuffer, error) {
buf := audio.IntBuffer{
Format: &audio.Format{
NumChannels: 1,
SampleRate: 8000,
},
}
for {
var sample int16
err := binary.Read(r, binary.LittleEndian, &sample)
switch {
case err == io.EOF:
return &buf, nil
case err != nil:
return nil, err
}
buf.Data = append(buf.Data, int(sample))
}
}
@harniruthwik
Copy link

how do we convert byte[] array to audio.IntBuffer ?

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