exp/i2s: loop recording 30 mins to file

This commit is contained in:
Trek Hopton 2024-02-14 16:08:49 +10:30
parent 89e530644d
commit 52b2bde9b4
1 changed files with 34 additions and 46 deletions

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"log" "log"
"os" "os"
"time" "time"
@ -10,29 +9,14 @@ import (
yalsa "github.com/yobert/alsa" yalsa "github.com/yobert/alsa"
) )
const i2sDevName = const i2sDevName = "simple-card_codec_link snd-soc-dummy-dai-0"
func main() { func main() {
// Set capture type. // Set capture type.
var i string var i2s bool = true
var i2s bool
fmt.Printf("Force I2S recording? (y/n): ")
fmt.Scan(&i)
if i == "y" {
i2s = true
} else {
i2s = false
}
// Set recording length. // Set recording length.
var duration time.Duration var duration time.Duration = 30 * time.Minute
var err error
fmt.Printf("Recording time: ")
fmt.Scan(&i)
duration, err = time.ParseDuration(i)
if err != nil {
duration = 5 * time.Second
}
// Find devices. // Find devices.
cards, err := yalsa.OpenCards() cards, err := yalsa.OpenCards()
@ -119,36 +103,40 @@ func main() {
return return
} }
buf := dev.NewBufferDuration(duration) // Record audio.
log.Println("recording for:", duration) for {
err = dev.Read(buf.Data) buf := dev.NewBufferDuration(duration)
if err != nil { log.Println("recording for:", duration)
log.Println("Failed to read:", err) err = dev.Read(buf.Data)
return if err != nil {
} log.Println("Failed to read:", err)
log.Println("Recording stopped.") return
}
log.Println("Recording stopped.")
file, err := os.Create("audio.wav") fileName := "audio-" + time.Now().Format("2006-01-02_15-04-05") + ".wav"
if err != nil { file, err := os.Create(fileName)
log.Println("failed to create file:", err) if err != nil {
return log.Println("failed to create file:", err)
} return
defer file.Close() }
defer file.Close()
var audio wav.WAV var audio wav.WAV
audio.Metadata = wav.Metadata{Channels: 2, AudioFormat: wav.PCMFormat, SampleRate: 44100, BitDepth: 16} audio.Metadata = wav.Metadata{Channels: 2, AudioFormat: wav.PCMFormat, SampleRate: 44100, BitDepth: 16}
_, err = audio.Write(buf.Data) _, err = audio.Write(buf.Data)
if err != nil { if err != nil {
log.Println("Failed to encode wav:", err) log.Println("Failed to encode wav:", err)
return return
} }
_, err = file.Write(audio.Audio) _, err = file.Write(audio.Audio)
if err != nil { if err != nil {
log.Println("failed to write audio:", err) log.Println("failed to write audio:", err)
return return
} }
log.Println("Audio saved to audio.wav") log.Println("Audio saved to audio.wav")
}
} }