Skip to content

Commit

Permalink
add sinusoid tone generation
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyapashuk committed Aug 24, 2021
1 parent 1c98bf6 commit 6521f34
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
20 changes: 20 additions & 0 deletions examples/tone-player/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import "os"
import "fmt"
import "github.com/faiface/beep"
import "github.com/faiface/beep/speaker"
import "strconv"

func main() {
f,_ := strconv.Atoi(os.Args[1])
speaker.Init(beep.SampleRate(48000), 4800)
s := beep.SinTone(beep.SampleRate(48000), f)
rb := make([][2]float64,20)
s.Stream(rb)
fmt.Println(rb)
speaker.Play(s)
for {

}
}
45 changes: 45 additions & 0 deletions toner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// tones generator


package beep

import "math"

// simple sinusoid tone generator
type toneStreamer struct {
stat float64
delta float64
}

// create streamer which will produce infinite sinusoid tone with the given frequency
// use other wrappers of this package to change amplitude or add time limit
// sampleRate must be at least two times grater then frequency, otherwise this function will panic
func SinTone(sr SampleRate, freq int) Streamer {
if int(sr) / freq < 2 {
panic("samplerate must be at least 2 times grater then frequency")
}
r := new(toneStreamer)
r.stat = 0.0
srf := float64(sr)
ff := float64(freq)
steps := srf / ff
r.delta = 1.0 / steps
return r
}

func (c *toneStreamer) nextSample() float64 {
r := math.Sin(c.stat * 2.0 * math.Pi)
_,c.stat = math.Modf(c.stat + c.delta)
return r
}

func (c *toneStreamer) Stream(buf [][2]float64) (int, bool) {
for i := 0; i < len(buf); i++ {
s := c.nextSample()
buf[i] = [2]float64{s,s}
}
return len(buf),true
}
func (_ *toneStreamer) Err() error {
return nil
}

0 comments on commit 6521f34

Please sign in to comment.