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
+5.4k Clean up Visual Studio For Mac installation failed disk full problem
+11.8k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+5.6k Golang : Frobnicate or tweaking a string example
+8.8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+7.3k Golang : Check to see if *File is a file or directory
+9.1k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+8.9k Golang : Capture text return from exec function example
+43k Golang : Convert []byte to image
+9.5k Golang : Sort and reverse sort a slice of floats
+22.8k Golang : Gorilla mux routing example
+22.6k Golang : Strings to lowercase and uppercase example
+8k Golang : HTTP Server Example