Golang : Detect sample rate, channels or latency with PortAudio




Problem:

You want to detect the sample rate, channels or latency of the input and output devices attached to your computer. Such as microphone and headphone. How to do that?

Solution:

We will use the Golang-PortAudio to extract the devices information that we want.

For example, if you are looking for the microphone's sample rate. The default input device detected can be Microsoft® LifeCam Cinema(TM with the sample rate of 44100

NOTES:

Using the wrong input sample rate will cause Input Overflowed error.

Here you go!


 package main

 import (
 "fmt"
 "github.com/gordonklaus/portaudio"
 )

 func main() {

 // init PortAudio

 portaudio.Initialize()

 detectedDevices, err := portaudio.Devices()

 if err != nil {
 panic(err)
 }

 fmt.Println("Detected audio input and output devices : ")
 for key, value := range detectedDevices {
 fmt.Printf("Key : %v , Value : %v\n", key, value)
 }

 fmt.Println("Default audio INPUT device : ")
 defaultInput, err := portaudio.DefaultInputDevice()

 if err != nil {
 panic(err)
 }

 // see https://godoc.org/github.com/gordonklaus/portaudio#DeviceInfo
 // for more details on Channels and Latency

 fmt.Printf("%v has sample rate of %v\n", defaultInput.Name, defaultInput.DefaultSampleRate)

 fmt.Println("Default audio OUTPUT device : ")
 defaultOutput, err := portaudio.DefaultOutputDevice()

 if err != nil {
 panic(err)
 }

 fmt.Printf("%v has sample rate of %v\n", defaultOutput.Name, defaultOutput.DefaultSampleRate)

 portaudio.Terminate()

 }

Sample output:

Detected audio input and output devices :

Key : 0 , Value : &{0 Microsoft® LifeCam Cinema(TM 1 0 3.71882ms 10ms 13.877551ms 100ms 44100 0xc420072140}

Key : 1 , Value : &{1 Line-out (Green Rear) 0 2 10ms 2.333333ms 100ms 11.666666ms 48000 0xc420072140}

Key : 2 , Value : &{2 Headphones (Green Front) 0 2 10ms 583.333µs 100ms 2.916666ms 192000 0xc420072140}

Key : 3 , Value : &{3 Microphone (Pink Rear) 2 0 2.333333ms 10ms 11.666666ms 100ms 48000 0xc420072140}

Key : 4 , Value : &{4 Microphone (Pink Front) 2 0 583.333µs 10ms 2.916666ms 100ms 192000 0xc420072140}

Default audio INPUT device :

Microsoft® LifeCam Cinema(TM has sample rate of 44100

Default audio OUTPUT device :

Headphones (Green Front) has sample rate of 192000

References:

https://godoc.org/github.com/gordonklaus/portaudio#DeviceInfo

https://socketloop.com/tutorials/golang-record-voice-audio-from-microphone-to-wav-file

  See also : Golang : Record voice(audio) from microphone to .WAV file





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement