/portaudio/examples/echo.go

https://code.google.com/p/portaudio-go/ · Go · 48 lines · 42 code · 6 blank · 0 comment · 5 complexity · 457b310a87c4c860774872809c1191b1 MD5 · raw file

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