2025-10-23 13:06:22 +07:00

94 lines
2.2 KiB
Go

package audio
import "math"
var _ Buffer = (*IntBuffer)(nil)
type IntBuffer struct {
Format *Format
Data []int
SourceBitDepth int
}
func (buf *IntBuffer) PCMFormat() *Format {
return buf.Format
}
func (buf *IntBuffer) AsFloatBuffer() *FloatBuffer {
newB := &FloatBuffer{}
newB.Data = make([]float64, len(buf.Data))
for i := 0; i < len(buf.Data); i++ {
newB.Data[i] = float64(buf.Data[i])
}
newB.Format = &Format{
NumChannels: buf.Format.NumChannels,
SampleRate: buf.Format.SampleRate,
}
return newB
}
func (buf *IntBuffer) AsFloat32Buffer() *Float32Buffer {
newB := &Float32Buffer{}
newB.Data = make([]float32, len(buf.Data))
max := int64(0)
if buf.SourceBitDepth == 0 {
for _, s := range buf.Data {
if int64(s) > max {
max = int64(s)
}
}
buf.SourceBitDepth = 8
if max > 127 {
buf.SourceBitDepth = 16
}
if max > 32767 {
buf.SourceBitDepth = 24
}
if max > 8388607 {
buf.SourceBitDepth = 32
}
if max > 4294967295 {
buf.SourceBitDepth = 64
}
}
newB.SourceBitDepth = buf.SourceBitDepth
factor := math.Pow(2, float64(buf.SourceBitDepth)-1)
for i := 0; i < len(buf.Data); i++ {
newB.Data[i] = float32(float64(buf.Data[i]) / factor)
}
newB.Format = &Format{
NumChannels: buf.Format.NumChannels,
SampleRate: buf.Format.SampleRate,
}
return newB
}
func (buf *IntBuffer) AsIntBuffer() *IntBuffer {
return buf
}
func (buf *IntBuffer) NumFrames() int {
if buf == nil || buf.Format == nil {
return 0
}
numChannels := buf.Format.NumChannels
if numChannels == 0 {
numChannels = 1
}
return len(buf.Data) / numChannels
}
func (buf *IntBuffer) Clone() Buffer {
if buf == nil {
return nil
}
newB := &IntBuffer{}
newB.Data = make([]int, len(buf.Data))
copy(newB.Data, buf.Data)
newB.Format = &Format{
NumChannels: buf.Format.NumChannels,
SampleRate: buf.Format.SampleRate,
}
return newB
}