Created
June 30, 2014 07:34
-
-
Save Darfk/02381be80bb7bd1e6032 to your computer and use it in GitHub Desktop.
Signal Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math" | |
"os/exec" | |
) | |
const ( | |
tau float64 = math.Pi * 2 | |
) | |
type Sin struct { | |
Vol float64 | |
Freq float64 | |
} | |
func (s *Sin) DSP(t float64) float64 { | |
return math.Sin(tau * s.Freq * t) * s.Vol | |
} | |
type Square struct { | |
Vol float64 | |
Freq float64 | |
} | |
func (s *Square) DSP(t float64) float64 { | |
if math.Sin(tau * s.Freq * t) > 0 { | |
return 1 * s.Vol | |
} | |
return -1 * s.Vol | |
} | |
type SigGen interface { | |
DSP(float64) float64 | |
} | |
type DDC struct { | |
Frame uint64 | |
Rate int32 | |
In SigGen | |
} | |
func (d *DDC) Read(p []byte) (n int, err error) { | |
for n=0; n < len(p); n++ { | |
var b float64 = (d.In.DSP(float64(d.Frame) / float64(d.Rate))/2+0.5) * 0xff | |
if b > 0xff { | |
b = 0xff | |
}else if b < 0x00 { | |
b = 0x00 | |
} | |
p[n] = byte(b) | |
d.Frame++ | |
} | |
return | |
} | |
type Mixer struct { | |
Ins []SigGen | |
} | |
func (m *Mixer) DSP(t float64) float64 { | |
var mix float64 = 0 | |
for n := 0; n < len(m.Ins); n++ { | |
mix += m.Ins[n].DSP(t) | |
} | |
return mix | |
} | |
func main() { | |
sin := new(Sin) | |
sin.Freq = 438 | |
sin.Vol = 0.2 | |
sqr := new(Square) | |
sqr.Freq = 440 | |
sqr.Vol = 0.2 | |
mxr := new(Mixer) | |
mxr.Ins = make([]SigGen, 2) | |
mxr.Ins[0] = sin | |
mxr.Ins[1] = sqr | |
ddc := new(DDC) | |
ddc.Rate = 44100 | |
ddc.In = mxr | |
cmd := exec.Command("pacat", "--format=u8", "--channels=1") | |
cmd.Stdin = ddc | |
cmd.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment