Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add sinusoid tone generation #127

Merged
merged 5 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
dusk125 marked this conversation as resolved.
Show resolved Hide resolved
}
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++ {
dusk125 marked this conversation as resolved.
Show resolved Hide resolved
s := c.nextSample()
buf[i] = [2]float64{s,s}
}
return len(buf),true
}
func (_ *toneStreamer) Err() error {
return nil
}