merge recognize-music.sh

This commit is contained in:
end-4
2026-04-05 21:55:32 +02:00
@@ -2,11 +2,8 @@
INTERVAL=2 INTERVAL=2
TOTAL_DURATION=30 TOTAL_DURATION=30
MIN_VALID_RESULT_LENGTH=300
SOURCE_TYPE="monitor" # monitor | input SOURCE_TYPE="monitor" # monitor | input
TMP_PATH="/tmp/quickshell/media/songrec" FIFO=$(mktemp -u /tmp/songrec_out_XXXXXX)
TMP_RAW="$TMP_PATH/recording.raw"
TMP_MP3="$TMP_PATH/recording.mp3"
while getopts "i:t:s:" opt; do while getopts "i:t:s:" opt; do
case $opt in case $opt in
@@ -16,47 +13,43 @@ while getopts "i:t:s:" opt; do
*) exit 1 ;; *) exit 1 ;;
esac esac
done done
if ! command -v songrec >/dev/null 2>&1; then
exit 1
fi
if [ "$SOURCE_TYPE" = "monitor" ]; then if [ "$SOURCE_TYPE" = "monitor" ]; then
MONITOR_SOURCE=$(pactl get-default-sink).monitor AUDIO_DEVICE=$(pactl get-default-sink).monitor
elif [ "$SOURCE_TYPE" = "input" ]; then elif [ "$SOURCE_TYPE" = "input" ]; then
MONITOR_SOURCE=$(pactl info | grep "Default Source:" | awk '{print $3}' || true) AUDIO_DEVICE=$(pactl info | grep "Default Source:" | awk '{print $3}' || true)
else else
echo "Invalid source type" echo "Invalid source type"
exit 1 exit 1
fi fi
if ! command -v songrec >/dev/null 2>&1 || ! command -v parec >/dev/null 2>&1 || ! command -v ffmpeg >/dev/null 2>&1; then if [ -z "$AUDIO_DEVICE" ] || ! pactl list short sources | grep -q "$AUDIO_DEVICE"; then
exit 1 exit 1
fi fi
if [ -z "$MONITOR_SOURCE" ] || ! pactl list short sources | grep -q "$MONITOR_SOURCE"; then mkfifo "$FIFO"
exit 1
fi
cleanup() { cleanup() {
rm -f "$TMP_RAW" "$TMP_MP3" kill "$SONGREC_PID" 2>/dev/null || true
pkill -P $$ parec >/dev/null 2>&1 || true wait "$SONGREC_PID" 2>/dev/null
rm -f "$FIFO"
} }
trap cleanup EXIT trap cleanup EXIT
mkdir -p "$TMP_PATH" songrec listen --audio-device "$AUDIO_DEVICE" --request-interval "$INTERVAL" --json --disable-mpris > "$FIFO" &
parec --device="$MONITOR_SOURCE" --format=s16le --rate=44100 --channels=2 > "$TMP_RAW" & SONGREC_PID=$!
START_TIME=$(date +%s)
while true; do ( sleep "$TOTAL_DURATION" && kill "$SONGREC_PID" 2>/dev/null ) &
sleep "$INTERVAL"
CURRENT_TIME=$(date +%s) while IFS= read -r line; do
ELAPSED=$((CURRENT_TIME - START_TIME)) if echo "$line" | grep -q '"matches": \['; then
echo "$line"
if (( ELAPSED >= TOTAL_DURATION )); then
exit 0 exit 0
fi fi
done < "$FIFO"
ffmpeg -f s16le -ar 44100 -ac 2 -i "$TMP_RAW" -acodec libmp3lame -y -hide_banner -loglevel error "$TMP_MP3" 2>/dev/null
RESULT=$(songrec recognize --json "$TMP_MP3" 2>/dev/null || true)
if echo "$RESULT" | grep -q '"matches": \[' && [ ${#RESULT} -gt $MIN_VALID_RESULT_LENGTH ]; then exit 0
echo "$RESULT"
exit 0
fi
done