sointu/go4k/audio/convertbuffer.go
Matias Lahti fa772ddd77 feat(go/audio): implement basic audio output with oto
splitting implementation into a separate package to potentially allow for other sorts of output, too.
2020-11-07 19:33:39 +02:00

23 lines
602 B
Go

package audio
import (
"bytes"
"encoding/binary"
"fmt"
"math"
)
// FloatBufferTo16BitLE is a naive helper method to convert []float32 buffers to
// 16-bit little-endian integer buffers.
// TODO: optimize/refactor this, current is far from the best solution
func FloatBufferTo16BitLE(buff []float32) ([]byte, error) {
var buf bytes.Buffer
for i, v := range buff {
uv := int16(v * math.MaxInt16)
if err := binary.Write(&buf, binary.LittleEndian, uv); err != nil {
return nil, fmt.Errorf("error converting buffer (@ %v, value %v) to bytes: %w", i, v, err)
}
}
return buf.Bytes(), nil
}