#!/bin/sh
# AwkBeat: a Busybox-compatible Bytebeat player with AWK syntax
# By default, SoX is required, or change the PLAYCMD variable to your engine
# (see some commented examples, some of them only accept 8Khz sample rate)
# Usage: awkbeat.sh 'formula'[ samplerate=8000]
# Example test on "42 melody": sh awkbeat.sh 't * and(42, rshift(t, 10))'
# Created in 2023 by Luxferre, released into public domain
FORMULA="$1"
SAMPLERATE="$2"
[ -z "$FORMULA" ] && printf 'No formula!\n' && exit
[ -z "$SAMPLERATE" ] && SAMPLERATE=8000

PLAYCMD="play -q -tu8 -r${SAMPLERATE} -c1 -" # most universal option with SoX play command
# or else uncomment one of these if you don't have SoX:
#PLAYCMD="tee /dev/dsp" # if you have bare OSS (only 8KHz input)
#PLAYCMD="aplay -q -f U8 -r ${SAMPLERATE}" # if you have ALSA
#PLAYCMD="pacat --raw --format=u8 --rate=${SAMPLERATE} --channels=1" # if you have PulseAudio
#PLAYCMD="pw-play --format=u8 --rate=${SAMPLERATE} --channels=1 -" # if you have PipeWire

printf 'AwkBeat by Luxferre\nPlaying formula: %s\nSample rate: %d Hz\n' "$FORMULA" "$SAMPLERATE"
# busybox awk doesn't support full byte output, so we print the stream in hex for xxd piping
APROG="BEGIN{for(t=0;t>-1;t++)printf(\"%02x\",and(255,int(${FORMULA})))}"
awk "$APROG" | xxd -r -p | $PLAYCMD > /dev/null # xxd is available in Busybox too
