377b6a6f0172aca710a417af8a02c4434641a986

Author
TheEdgeOfRage <git@theedgeofrage.com>
Committer
TheEdgeOfRage <git@theedgeofrage.com>
Date

Message

Add timeout to fix aplay hang

Diff

 1diff --git a/AGENTS.md b/AGENTS.md
 2index 335a55ff19579fc18d2ad665d33e2bf7d6711f6b..42cac043aa4915f3e59517ff29b3f04e6a47d254 100644
 3--- a/AGENTS.md
 4+++ b/AGENTS.md
 5@@ -36,3 +36,7 @@ Single `main` package, one file per concern:
 6 - External dependencies are ffmpeg, ffprobe, and aplay — shell out to them
 7   rather than adding Go audio libraries.
 8 - Check with `golangci-lint ./...` after changes.
 9+
10+## Important instructions
11+
12+- Never search for music files yourself. Just use the default catalog already in the code
13diff --git a/audio.go b/audio.go
14index 3387dfef98e593dae791a56f48f0fc67ed0f23ee..7814a4703fe6369c69956ef30dfbbdb89238291d 100644
15--- a/audio.go
16+++ b/audio.go
17@@ -2,6 +2,7 @@ package main
18 
19 import (
20 	"bytes"
21+	"context"
22 	"encoding/binary"
23 	"fmt"
24 	"math"
25@@ -10,6 +11,7 @@ import (
26 	"os/exec"
27 	"strconv"
28 	"strings"
29+	"time"
30 )
31 
32 const (
33@@ -52,7 +54,7 @@ func findStart(samples []int16) int {
34 	rmsVals := make([]float64, 0, len(samples)/win)
35 	var sum float64
36 	for i := 0; i+win <= len(samples); i += win {
37-		v := rms(samples[i:i+win])
38+		v := rms(samples[i : i+win])
39 		rmsVals = append(rmsVals, v)
40 		sum += v
41 	}
42@@ -146,11 +148,13 @@ func playSegment(songPath string, startSec, seconds int) error {
43 	if err != nil {
44 		return err
45 	}
46-	cmd := exec.Command("aplay", "-q")
47+	// timeout to fix aplay hang
48+	timeout := time.Duration(seconds)*time.Second + 200*time.Millisecond
49+	ctx, cancel := context.WithTimeout(context.Background(), timeout)
50+	defer cancel()
51+	cmd := exec.CommandContext(ctx, "aplay", "-q")
52 	cmd.Stdin = bytes.NewReader(wav)
53 	cmd.Stdout = os.Stderr
54 	cmd.Stderr = os.Stderr
55 	return cmd.Run()
56 }
57-
58-