Debian Codegraph @

examples/sinewave.go

raw symbols SCIP
1 // generate some simple tones and play them on the default audio output.
2 //
3 // to run this example, simply `go run examples/sinewave.go`.
4 package main
5
6 import (
7 ".." // pulse-simple
8 "encoding/binary"
9 "fmt"
10 "math"
11 )
12
13 func main() {
14 ss := pulse.SampleSpec{pulse.SAMPLE_FLOAT32LE, 44100, 1}
15 pb, err := pulse.Playback("pulse-simple test", "playback test", &ss)
16 defer pb.Free()
17 defer pb.Drain()
18 if err != nil {
19 fmt.Printf("Could not create playback stream: %s\n", err)
20 return
21 }
22 playsine(pb, &ss)
23 }
24
25 func playsine(s *pulse.Stream, ss *pulse.SampleSpec) {
26 num_notes := 5
27 f := []float64{220, 247, 277, 294, 330}
28 n := []string{"A3", "B3", "C#4", "D4", "E4"}
29 r := float64(ss.Rate)
30 data := make([]byte, 4*ss.Rate)
31 tau := 2 * math.Pi
32 for j := 0; j < num_notes; j++ {
33 fmt.Printf("%v\n", n[j])
34 for i := 0; i < int(ss.Rate); i++ {
35 // (f) Hz sine wave, with 0.5Hz sine envelope over 1 second duration
36 sample := float32((math.Sin(tau*f[j]*float64(i)/r) / 3.0) *
37 math.Sin((tau/2.0)*float64(i)/r))
38 bits := math.Float32bits(sample)
39 binary.LittleEndian.PutUint32(data[4*i:4*i+4], bits)
40 }
41 s.Write(data)
42 }
43 }