57 lines
1.0 KiB
Go
57 lines
1.0 KiB
Go
package audio
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"fmt"
|
|
"math"
|
|
)
|
|
|
|
type Buffer struct {
|
|
Buf []byte
|
|
Ch int
|
|
Format Format
|
|
}
|
|
|
|
// NewBuffer returns a buffer of n samples and ch channels.
|
|
func NewBuffer(n, ch int, f Format) *Buffer {
|
|
if ch < 1 {
|
|
ch = 1
|
|
}
|
|
return &Buffer{
|
|
Buf: make([]byte, n*ch*f.BytesPerSample()),
|
|
Ch: ch,
|
|
Format: f,
|
|
}
|
|
}
|
|
|
|
func (b *Buffer) Decode(data any, order binary.ByteOrder) (n int, err error) {
|
|
switch data := data.(type) {
|
|
case []int8:
|
|
var x byte
|
|
for n, x = range b.Buf {
|
|
data[n] = int8(x)
|
|
}
|
|
case []uint8:
|
|
n = copy(data, b.Buf)
|
|
case []int16:
|
|
for n = range data {
|
|
data[n] = int16(order.Uint16(b.Buf[n<<1:]))
|
|
}
|
|
case []int32:
|
|
for n = range data {
|
|
data[n] = int32(order.Uint32(b.Buf[n<<2:]))
|
|
}
|
|
case []float32:
|
|
for n = range data {
|
|
data[n] = math.Float32frombits(order.Uint32(b.Buf[n<<2:]))
|
|
}
|
|
case []float64:
|
|
for n = range data {
|
|
data[n] = math.Float64frombits(order.Uint64(b.Buf[n<<3:]))
|
|
}
|
|
default:
|
|
return 0, fmt.Errorf("can't decode to %T", data)
|
|
}
|
|
return
|
|
}
|