examples/sinewave: refactoring

This commit is contained in:
Hajime Hoshi 2024-07-22 23:12:50 +09:00
parent f717844076
commit fd382d26ae

View File

@ -33,30 +33,20 @@ const (
// stream is an infinite stream of 440 Hz sine wave. // stream is an infinite stream of 440 Hz sine wave.
type stream struct { type stream struct {
position int64 pos int64
remaining []byte
} }
// Read is io.Reader's Read. // Read is io.Reader's Read.
// //
// Read fills the data with sine wave samples. // Read fills the data with sine wave samples.
func (s *stream) Read(buf []byte) (int, error) { func (s *stream) Read(buf []byte) (int, error) {
if len(s.remaining) > 0 { const bytesPerSample = 8
n := copy(buf, s.remaining)
s.remaining = s.remaining[n:]
return n, nil
}
var origBuf []byte n := len(buf) / bytesPerSample * bytesPerSample
if len(buf)%8 > 0 {
origBuf = buf
buf = make([]byte, len(origBuf)+8-len(origBuf)%8)
}
const length = int64(sampleRate / frequency) const length = sampleRate / frequency
p := s.position / 8 for i := 0; i < n/bytesPerSample; i++ {
for i := 0; i < len(buf)/8; i++ { v := math.Float32bits(float32(math.Sin(2 * math.Pi * float64(s.pos/bytesPerSample+int64(i)) / length)))
v := math.Float32bits(float32(math.Sin(2 * math.Pi * float64(p) / float64(length))))
buf[8*i] = byte(v) buf[8*i] = byte(v)
buf[8*i+1] = byte(v >> 8) buf[8*i+1] = byte(v >> 8)
buf[8*i+2] = byte(v >> 16) buf[8*i+2] = byte(v >> 16)
@ -65,18 +55,12 @@ func (s *stream) Read(buf []byte) (int, error) {
buf[8*i+5] = byte(v >> 8) buf[8*i+5] = byte(v >> 8)
buf[8*i+6] = byte(v >> 16) buf[8*i+6] = byte(v >> 16)
buf[8*i+7] = byte(v >> 24) buf[8*i+7] = byte(v >> 24)
p++
} }
s.position += int64(len(buf)) s.pos += int64(n)
s.position %= length * 8 s.pos %= length * bytesPerSample
if origBuf != nil { return n, nil
n := copy(origBuf, buf)
s.remaining = buf[n:]
return n, nil
}
return len(buf), nil
} }
// Close is io.Closer's Close. // Close is io.Closer's Close.