Golang : Play .WAV file from command line
Problem:
You have recorded your voice on a .wav
file with the previous tutorial on how to activate your microphone, record your voice and save the data into a .wav file from command line.
Now, you want to play back the .wav
file from command line.
How to do that?
Solution:
The approach is similar to how the voice in recorded with PlayAudio and encode with wave.Write()
function with the exception that this time is to read the .wav
file with wave.NewReader()
first.
Read the raw data with waveReader.ReadRawSample()
and transfer the data into a buffer before writing out to PortAudio.
Here you go!
playwav.go
package main
import (
"fmt"
"github.com/gordonklaus/portaudio"
wave "github.com/zenwerk/go-wave"
"math/rand"
"os"
"os/signal"
"time"
)
func errCheck(err error) {
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <audiofilename.wav>\n", os.Args[0])
os.Exit(0)
}
audioFileName := os.Args[1]
fmt.Println("Playing [" + audioFileName + "] Press Ctrl-C to stop.")
waveReader, err := wave.NewReader(audioFileName)
errCheck(err)
// init PortAudio
portaudio.Initialize()
defer portaudio.Terminate()
inputChannels := 0
outputChannels := 1
sampleRate := 44100
framesPerBuffer := make([]byte, 1024)
stream, err := portaudio.OpenDefaultStream(inputChannels, outputChannels, float64(sampleRate), len(framesPerBuffer), &framesPerBuffer)
errCheck(err)
defer stream.Close()
// recording in progress ticker. From good old DOS days.
ticker := []string{
"-",
"\\",
"/",
"|",
}
rand.Seed(time.Now().UnixNano())
errCheck(stream.Start())
defer stream.Stop()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
READERROR:
for {
// read into buffer to be played
//_, err := waveReader.Read(framesPerBuffer)
framesPerBuffer, err = waveReader.ReadRawSample()
if err != nil {
fmt.Println(err.Error())
break READERROR
}
errCheck(stream.Write())
fmt.Printf("\rPlaying now! [%v]", ticker[rand.Intn(len(ticker)-1)])
select {
case <-sig:
return
default:
}
}
if waveReader.NumSamples != waveReader.ReadSampleNum {
fmt.Printf("Actual samples : %d\nRead samples : %d\n", waveReader.NumSamples, waveReader.ReadSampleNum)
fmt.Println(waveReader.NumSamples, waveReader.ReadSampleNum)
} else {
fmt.Println("Wave file played without error")
}
}
References:
https://github.com/zenwerk/go-wave/blob/master/reader.go
http://people.csail.mit.edu/hubert/pyaudio/
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
Tutorials
+21k SSL : How to check if current certificate is sha1 or sha2
+15.8k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+25k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+35.5k Golang : Validate IP address
+14.6k Golang : Get HTTP protocol version example
+12k Golang : Exit, terminating or aborting a program
+12k Golang : Arithmetic operation with numerical slices or arrays example
+6.8k Golang : Not able to grep log.Println() output
+16.8k Golang : Multi threading or run two processes or more example
+9.6k Golang : Get escape characters \u form from unicode characters
+21.2k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+19k Golang : How to count the number of repeated characters in a string?