From 22a2af6eaf73ab1604a73d81201c3faae1466eb9 Mon Sep 17 00:00:00 2001 From: Phil Howard Date: Wed, 31 Jul 2024 10:49:32 +0100 Subject: [PATCH] audio: Add wave shapes. --- boards/PIMORONI_TINYFX/visible_libs/audio.py | 23 ++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/boards/PIMORONI_TINYFX/visible_libs/audio.py b/boards/PIMORONI_TINYFX/visible_libs/audio.py index 0a2708c..e10cdc1 100644 --- a/boards/PIMORONI_TINYFX/visible_libs/audio.py +++ b/boards/PIMORONI_TINYFX/visible_libs/audio.py @@ -90,6 +90,10 @@ class WavPlayer: MODE_WAV = 0 MODE_TONE = 1 + TONE_SINE = 0 + TONE_SQUARE = 1 + TONE_TRIANGLE = 2 + # Default buffer length SILENCE_BUFFER_LENGTH = 1024 WAV_BUFFER_LENGTH = 1024 @@ -107,6 +111,9 @@ def __init__(self, id, sck_pin, ws_pin, sd_pin, amp_enable=None, ibuf_len=INTERN self.__ibuf_len = ibuf_len self.__enable = None + # Manually tweak the tone amplitude for equal loudness of sine/square/triangle + self.__amplitude_scale = [1.0, 0.2, 0.5] + if amp_enable is not None: self.__enable = Pin(amp_enable, Pin.OUT) @@ -152,25 +159,33 @@ def play_wav(self, wav_file, loop=False): state=WavPlayer.PLAY, mode=WavPlayer.MODE_WAV) - def play_tone(self, frequency, amplitude): + def play_tone(self, frequency, amplitude, shape=TONE_SINE): if frequency < 20.0 or frequency > 20_000: raise ValueError("frequency out of range. Expected between 20Hz and 20KHz") if amplitude < 0.0 or amplitude > 1.0: raise ValueError("amplitude out of range. Expected 0.0 to 1.0") + amplitude *= self.__amplitude_scale[shape] + # Create a buffer containing the pure tone samples samples_per_cycle = self.TONE_SAMPLE_RATE // frequency sample_size_in_bytes = self.TONE_BITS_PER_SAMPLE // 8 samples = bytearray(self.TONE_FULL_WAVES * samples_per_cycle * sample_size_in_bytes) - range = pow(2, self.TONE_BITS_PER_SAMPLE) // 2 + maximum = (pow(2, self.TONE_BITS_PER_SAMPLE) // 2 - 1) * amplitude format = "