DataHoarder
449b38272b
All checks were successful
continuous-integration/drone/push Build is passing
Removed AnalyzerChannel in favor of raw samples
100 lines
2 KiB
Go
100 lines
2 KiB
Go
package audio
|
|
|
|
type Stream struct {
|
|
source Source
|
|
channel chan []float32
|
|
samplesProcessed int
|
|
buffer []float32
|
|
blockSize int
|
|
}
|
|
|
|
func NewStream(source Source, blockSize int) *Stream {
|
|
return &Stream{
|
|
source: source,
|
|
blockSize: blockSize,
|
|
}
|
|
}
|
|
|
|
func (s *Stream) GetChannels() int {
|
|
return s.source.GetChannels()
|
|
}
|
|
|
|
func (s *Stream) GetSampleRate() int {
|
|
return s.source.GetSampleRate()
|
|
}
|
|
|
|
func (s *Stream) GetSamplesProcessed() int {
|
|
return s.samplesProcessed
|
|
}
|
|
|
|
func (s *Stream) GetAsChannel() chan float32 {
|
|
newChannel := make(chan float32)
|
|
go func() {
|
|
defer close(newChannel)
|
|
for {
|
|
v, more := s.Get()
|
|
if !more {
|
|
return
|
|
}
|
|
newChannel <- v
|
|
s.samplesProcessed++
|
|
}
|
|
}()
|
|
return newChannel
|
|
}
|
|
|
|
func (s *Stream) GetAsBlockChannel() chan []float32 {
|
|
newChannel := make(chan []float32)
|
|
|
|
go func() {
|
|
defer close(newChannel)
|
|
for buf := range s.source.ToFloat32().GetBlocks() {
|
|
s.buffer = append(s.buffer, buf...)
|
|
for len(s.buffer) >= s.blockSize*s.source.GetChannels() {
|
|
newChannel <- s.buffer[0 : s.blockSize*s.source.GetChannels()]
|
|
s.samplesProcessed += s.blockSize * s.source.GetChannels()
|
|
s.buffer = s.buffer[s.blockSize*s.source.GetChannels():]
|
|
}
|
|
}
|
|
|
|
if len(s.buffer) > 0 {
|
|
newChannel <- s.buffer
|
|
s.samplesProcessed += len(s.buffer)
|
|
}
|
|
s.buffer = nil
|
|
}()
|
|
return newChannel
|
|
}
|
|
|
|
func (s *Stream) Get() (float32, bool) {
|
|
if s.channel == nil {
|
|
s.channel = s.source.ToFloat32().GetBlocks()
|
|
}
|
|
var more bool
|
|
if len(s.buffer) == 0 {
|
|
s.buffer, more = <-s.channel
|
|
if !more {
|
|
return 0, false
|
|
}
|
|
}
|
|
f := s.buffer[0]
|
|
s.buffer = s.buffer[1:]
|
|
s.samplesProcessed++
|
|
return f, true
|
|
}
|
|
|
|
func (s *Stream) AdvanceSeconds(seconds float64) bool {
|
|
stopAt := s.secondsIndex(seconds)
|
|
for i := 0; i < stopAt; i++ {
|
|
_, more := s.Get()
|
|
if !more {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Stream) secondsIndex(seconds float64) int {
|
|
return int(seconds * float64(s.source.GetSampleRate()))
|
|
}
|