@@ -72,42 +72,46 @@ def audio_to_makecode_arcade(data, sample_rate, period) -> str:
7272 )
7373
7474 frequency_buckets = [50 , 159 , 200 , 252 , 317 , 400 , 504 , 635 , 800 , 1008 ,
75- 1270 , 1600 , 2016 , 2504 , 3200 , 4032 , 5080 , 7000 , 9000 , 10240 ]
75+ 1270 , 1600 , 2016 , 2504 , 3200 , 4032 , 5080 , 7000 , 9000 ]
7676
7777 max_freqs = 30
7878 loudest_indices = np .argsort (Sxx , axis = 0 )[- max_freqs :]
7979 loudest_frequencies = f [loudest_indices ].transpose ()
8080 loudest_amplitudes = Sxx [loudest_indices , np .arange (Sxx .shape [1 ])].transpose ()
8181 max_amp = np .max (Sxx )
8282
83- # Smooth amplitudes for cleaner sound
83+ # Smooth amplitudes
8484 loudest_amplitudes = moving_average_2d (loudest_amplitudes , window_size = 3 )
8585
86- sound_instruction_buffers = ["" ] * len (frequency_buckets )
86+ # Create dedicated threads per bucket
87+ threads = [[] for _ in frequency_buckets ]
8788
8889 for slice_index in range (len (loudest_frequencies )):
89- freqs = loudest_frequencies [slice_index ]
90- amps = loudest_amplitudes [slice_index ]
90+ prev_bucket_high = 0
91+ for bucket_index , bucket_high in enumerate (frequency_buckets ):
92+ freqs = loudest_frequencies [slice_index ]
93+ amps = loudest_amplitudes [slice_index ]
9194
92- for bucket_index in range (len (frequency_buckets )):
93- low = frequency_buckets [bucket_index - 1 ] if bucket_index > 0 else 0
94- high = frequency_buckets [bucket_index ]
95- freq_index = - 1
95+ # pick the loudest frequency in this bucket range
96+ freq_idx = - 1
9697 for i in range (len (freqs )- 1 , - 1 , - 1 ):
97- if low <= freqs [i ] <= high :
98- freq_index = i
98+ if prev_bucket_high <= freqs [i ] <= bucket_high :
99+ freq_idx = i
99100 break
100- if freq_index != - 1 :
101- freq = round (freqs [freq_index ])
102- amp = round (amps [freq_index ] / max_amp * 1024 )
103- sound_instruction_buffers [bucket_index ] += create_sound_instruction (freq , freq , amp , amp , period )
101+
102+ if freq_idx != - 1 :
103+ freq = round (freqs [freq_idx ])
104+ amp = round (amps [freq_idx ] / max_amp * 1024 )
105+ threads [bucket_index ].append (create_sound_instruction (freq , freq , amp , amp , period ))
104106 else :
105- sound_instruction_buffers [bucket_index ] += create_sound_instruction (0 , 0 , 0 , 0 , period )
107+ threads [bucket_index ].append (create_sound_instruction (0 , 0 , 0 , 0 , period ))
108+
109+ prev_bucket_high = bucket_high
106110
107111 # Wrap each buffer in hex`` properly
108- sound_instruction_buffers = [f"hex`{ buf } `" for buf in sound_instruction_buffers ]
112+ sound_instruction_buffers = [f"hex`{ '' . join ( thread ) } `" for thread in threads ]
109113
110- # Only queuePlayInstructions function to avoid duplicates
114+ # MakeCode TS code (only queuePlayInstructions)
111115 code = (
112116 "namespace music {\n "
113117 " //% shim=music::queuePlayInstructions\n "
0 commit comments