Debian Codegraph @

examples/echo.go

raw symbols SCIP
1 // capture some audio from the default device, and play it back.
2 //
3 // to run this example, simply `go run examples/echo.go`.
4 package main
5
6 import (
7 ".." // pulse-simple
8 "encoding/binary"
9 "fmt"
10 "math"
11 )
12
13 func main() {
14 // define the sample spec we want,
15 // in this case single-channel 44100Hz little-endian 32-bit float.
16 ss := pulse.SampleSpec{pulse.SAMPLE_FLOAT32LE, 44100, 1}
17
18 // create the capture device and audio storage buffers
19 capture, err := pulse.Capture("pulse-simple test", "capture test", &ss)
20 defer capture.Free()
21 if err != nil {
22 fmt.Printf("Could not create capture stream: %s\n", err)
23 return
24 }
25 storage := make([]byte, 44100*4)
26 // 1/25 second buffer for volume meter and stop button responsiveness
27 buffer := make([]byte, 44100*4/25)
28 fmt.Println("Recording... (press ENTER to finish capture)")
29
30 // wait in the background for the user to press enter
31 stop := make(chan bool)
32 go func() {
33 var input string
34 fmt.Scanln(&input)
35 stop <- true
36 }()
37
38 // until the user presses enter, continue to capture audio
39 Capture:
40 for {
41 select {
42 case <-stop:
43 break Capture
44 default:
45 _, err := capture.Read(buffer)
46 if err != nil {
47 fmt.Printf("Aborting due to audio capture error: %s\n", err)
48 break Capture
49 }
50 storage = append(storage, buffer...)
51 // also display a crude volume-meter
52 display_volume(buffer)
53 }
54 }
55 fmt.Print("\r") // overwrite the enter from input
56
57 // create playback stream and play back the captured audio
58 playback, err := pulse.Playback("pulse-simple test", "playback test", &ss)
59 defer playback.Free()
60 defer playback.Drain()
61 if err != nil {
62 fmt.Printf("Could not create playback stream: %s\n", err)
63 return
64 }
65 fmt.Println("Playing back recorded audio...")
66 playback.Write(storage)
67 }
68
69 func display_volume(buffer []byte) {
70 numsamples := len(buffer) / 4
71 sumsquares := float64(0)
72 for i := 0; i < numsamples; i++ {
73 bits := binary.LittleEndian.Uint32(buffer[4*i : 4*i+4])
74 value := math.Float32frombits(bits)
75 sumsquares += float64(value * value)
76 }
77 // root mean square of the signal should give an approximation of volume
78 volume := math.Sqrt(sumsquares / float64(numsamples))
79
80 // print between 0 and 40 '#' characters as a volume meter
81 maxvolume := 0.5
82 fmt.Print("\r")
83 for i := 0.0; i < maxvolume; i += maxvolume / 40 {
84 if i < volume {
85 fmt.Print("#")
86 } else {
87 fmt.Print(" ")
88 }
89 }
90 }