go-audio / wav

Battle tested Wav decoder/encoder
Apache License 2.0
309 stars 46 forks source link

WriteFrame() could accept a slice #18

Open ivoras opened 5 years ago

ivoras commented 5 years ago

I keep my PCM audio samples as []int16, and while learning to use this library, it seemed natural to use it like this:

data := []int16{...}
enc := wav.NewEncoder(f, 44100, 16, 1, 1)
if err := enc.WriteFrame(data); err != nil {
  panic(err)
}
enc.Close()

The reason why this seemed like a good idea is that WriteFrame() calls AddLE() and this ultimately calls binary.Write() which in addition to integers accepts slices of integers. The resulting file has the correct size.

BUT... WriteFrame() (at line https://github.com/go-audio/wav/blob/master/encoder.go#L217) only increments the frame count by one, which makes the WAV headers only recognize a single sample. If this were handled so that WriteFrame() checks for a slice argument, and/or a separate function WriteFrames() is added to write the whole slice at once, it would simplify the library's usage.

Edit:

The alternative approach:

for _, sample := range data {
  enc.WriteFrame(sample)
}

...is horribly slow. It takes several seconds to write a 2 MB buffer! This is because binary.Write() issues a write syscall for every single call, i.e. for every single sample!

Created a pull request.