I'm working on a lighting application based on audio, similar to a Christmas light setup with music. I'm going to set up the pi to drive a relay. The basic idea is I want the relay open during quiet parts of the audio and closed during loud parts. Here's the approach I have taken:
For each sample in the 44.1kHz audio file, if the amplitude is greater than the arbitrary threshold, write 1 to file; else, 0. This gives me a file of 0s and 1s equal in length to 44100 bits * seconds duration of the audio file. I want to "play" those 0s and 1s (simultaneous to the actual audio in speakers) to a gpio pin at 44.1kHz. How best can I accomplish this? Multiple calls to delay() would seem to lack the necessary precision.
FWIW the relay takes about 1ms to switch, so it can't operate at 44100 switches per second, but naturally there are long stretches of 0s and 1s from the audio file so switching is sparse. I considered converting the 0s and 1s to ON and OFF calls with delay() in-between, but I worry about drift because delay() is not guaranteed to return exactly after the number of ms specified. This could lead to loss of sync over long audio files.
I'm also aware that there are some really nice libraries for Christmas light setups. I'm using this project as mostly a learning experience. Also, the libraries I've seen use FFT or other automated means of controlling the lights, but I'd like to eventual jump from using amplitude as a delimiter, to making my own custom on-off cue files.