Skip to content

Commit 6a3b6d8

Browse files
Update main.py
1 parent 4c499ad commit 6a3b6d8

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

main.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ def create_sound_instruction(start_freq: int, end_freq: int, start_vol: int,
5959
).hex()
6060

6161

62+
def moving_average(arr, window_size=3):
63+
"""Simple smoothing with a centered moving average."""
64+
if window_size < 2:
65+
return arr
66+
return np.convolve(arr, np.ones(window_size)/window_size, mode="same")
67+
68+
6269
def audio_to_makecode_arcade(data, sample_rate, period) -> str:
6370
spectrogram_frequency = period / 1000
6471
if can_log:
@@ -70,6 +77,7 @@ def audio_to_makecode_arcade(data, sample_rate, period) -> str:
7077
nperseg=round(spectrogram_frequency * sample_rate)
7178
)
7279

80+
# --- Frequency bucket ranges ---
7381
frequency_buckets = [50, 159, 200, 252, 317, 400, 504, 635, 800, 1008,
7482
1270, 1600, 2016, 2504, 3200, 4032, 5080, 7000, 9000, 10240]
7583

@@ -82,8 +90,13 @@ def audio_to_makecode_arcade(data, sample_rate, period) -> str:
8290
sound_instruction_buffers = [""] * len(frequency_buckets)
8391

8492
for slice_index in range(len(loudest_frequencies)):
93+
freqs = loudest_frequencies[slice_index]
94+
amps = loudest_amplitudes[slice_index]
95+
96+
# Smooth amplitudes a little
97+
amps = moving_average(amps, window_size=3)
98+
8599
for bucket_index in range(len(frequency_buckets)):
86-
freqs = loudest_frequencies[slice_index]
87100
low = frequency_buckets[bucket_index - 1] if bucket_index > 0 else 0
88101
high = frequency_buckets[bucket_index]
89102
freq_index = -1
@@ -93,9 +106,10 @@ def audio_to_makecode_arcade(data, sample_rate, period) -> str:
93106
break
94107
if freq_index != -1:
95108
freq = round(freqs[freq_index])
96-
amp = round(loudest_amplitudes[slice_index, freq_index] / max_amp * 1024)
109+
amp = round(amps[freq_index] / max_amp * 1024)
97110
sound_instruction_buffers[bucket_index] += create_sound_instruction(freq, freq, amp, amp, period)
98111
else:
112+
# silence
99113
sound_instruction_buffers[bucket_index] += create_sound_instruction(0, 0, 0, 0, period)
100114

101115
# Wrap each buffer in hex`` properly

0 commit comments

Comments
 (0)