add Take decorator function
This commit is contained in:
parent
f3e2b915bd
commit
5723022b5a
|
@ -1,5 +1,28 @@
|
|||
package audio
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Take returns a Streamer which streams s for at most d duration.
|
||||
func Take(d time.Duration, s Streamer) Streamer {
|
||||
currSample := 0
|
||||
numSamples := int(math.Ceil(d.Seconds() * SampleRate))
|
||||
return StreamerFunc(func(samples [][2]float64) (n int, ok bool) {
|
||||
if currSample >= numSamples {
|
||||
return 0, false
|
||||
}
|
||||
toStream := numSamples - currSample
|
||||
if len(samples) < toStream {
|
||||
toStream = len(samples)
|
||||
}
|
||||
sn, sok := s.Stream(samples[:toStream])
|
||||
currSample += sn
|
||||
return sn, sok
|
||||
})
|
||||
}
|
||||
|
||||
// Seq takes zero or more Streamers and returns a Streamer which streams them one by one without pauses.
|
||||
func Seq(s ...Streamer) Streamer {
|
||||
i := 0
|
||||
|
|
|
@ -44,6 +44,22 @@ func collect(s audio.Streamer) [][2]float64 {
|
|||
}
|
||||
}
|
||||
|
||||
func TestTake(t *testing.T) {
|
||||
for i := 0; i < 7; i++ {
|
||||
total := time.Nanosecond * time.Duration(1e8+rand.Intn(1e9))
|
||||
s, data := randomDataStreamer(total)
|
||||
d := time.Nanosecond * time.Duration(rand.Int63n(total.Nanoseconds()))
|
||||
numSamples := int(math.Ceil(d.Seconds() * audio.SampleRate))
|
||||
|
||||
want := data[:numSamples]
|
||||
got := collect(audio.Take(d, s))
|
||||
|
||||
if !reflect.DeepEqual(want, got) {
|
||||
t.Error("Take not working correctly")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeq(t *testing.T) {
|
||||
var (
|
||||
s = make([]audio.Streamer, 7)
|
||||
|
|
Loading…
Reference in New Issue