PageRenderTime 171ms CodeModel.GetById 61ms app.highlight 4ms RepoModel.GetById 46ms app.codeStats 0ms

/portaudio/examples/echo.go

https://code.google.com/p/portaudio-go/
Go | 48 lines | 42 code | 6 blank | 0 comment | 3 complexity | 457b310a87c4c860774872809c1191b1 MD5 | raw file
 1package main
 2
 3import (
 4	"code.google.com/p/portaudio-go/portaudio"
 5	"time"
 6)
 7
 8func main() {
 9	portaudio.Initialize()
10	defer portaudio.Terminate()
11	e := newEcho(time.Second / 3)
12	defer e.Close()
13	chk(e.Start())
14	time.Sleep(4 * time.Second)
15	chk(e.Stop())
16}
17
18type echo struct {
19	*portaudio.Stream
20	buffer []float32
21	i      int
22}
23
24func newEcho(delay time.Duration) *echo {
25	h, err := portaudio.DefaultHostApi()
26	chk(err)
27	p := portaudio.LowLatencyParameters(h.DefaultInputDevice, h.DefaultOutputDevice)
28	p.Input.Channels = 1
29	p.Output.Channels = 1
30	e := &echo{buffer: make([]float32, int(p.SampleRate*delay.Seconds()))}
31	e.Stream, err = portaudio.OpenStream(p, e.processAudio)
32	chk(err)
33	return e
34}
35
36func (e *echo) processAudio(in, out []float32) {
37	for i := range out {
38		out[i] = .7 * e.buffer[e.i]
39		e.buffer[e.i] = in[i]
40		e.i = (e.i + 1) % len(e.buffer)
41	}
42}
43
44func chk(err error) {
45	if err != nil {
46		panic(err)
47	}
48}