Skip to content

Commit a76e141

Browse files
committed
codal_port/modmusic: Make music.pitch stop any ongoing background music.
Also fix music.play and music.stop to stop ongoing background music before changing any other music parameters. Signed-off-by: Damien George <damien@micropython.org>
1 parent faf83c1 commit a76e141

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/codal_port/modmusic.c

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -284,9 +284,14 @@ STATIC mp_obj_t microbit_music_stop(mp_uint_t n_args, const mp_obj_t *args) {
284284
}
285285
// Raise exception if the pin we are trying to stop is not in a compatible mode.
286286
microbit_pin_audio_select(pin);
287+
288+
// Stop any ongoing background music
289+
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
290+
291+
// Turn off the output and free the audio pin
287292
music_output_amplitude(MUSIC_OUTPUT_AMPLITUDE_OFF);
288293
microbit_pin_audio_free();
289-
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
294+
290295
return mp_const_none;
291296
}
292297
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(microbit_music_stop_obj, 0, 1, microbit_music_stop);
@@ -317,14 +322,16 @@ STATIC mp_obj_t microbit_music_play(mp_uint_t n_args, const mp_obj_t *pos_args,
317322
mp_obj_get_array(args[0].u_obj, &len, &items);
318323
}
319324

325+
// Stop any ongoing background music
326+
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
327+
320328
// Release the previous pin
321329
microbit_pin_audio_free();
322330

323331
// get the pin to play on
324332
microbit_pin_audio_select(args[1].u_obj);
325333

326334
// start the tune running in the background
327-
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
328335
music_data->async_wait_ticks = mp_hal_ticks_ms();
329336
music_data->async_loop = args[3].u_bool;
330337
music_data->async_notes_len = len;
@@ -364,6 +371,9 @@ STATIC mp_obj_t microbit_music_pitch(mp_uint_t n_args, const mp_obj_t *pos_args,
364371
mp_uint_t frequency = args[0].u_int;
365372
mp_int_t duration = args[1].u_int;
366373

374+
// Stop any ongoing background music
375+
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
376+
367377
// Update pin modes
368378
microbit_pin_audio_free();
369379
microbit_pin_audio_select(args[2].u_obj);
@@ -378,7 +388,6 @@ STATIC mp_obj_t microbit_music_pitch(mp_uint_t n_args, const mp_obj_t *pos_args,
378388
}
379389
if (duration >= 0) {
380390
// use async machinery to stop the pitch after the duration
381-
music_data->async_state = ASYNC_MUSIC_STATE_IDLE;
382391
music_data->async_wait_ticks = mp_hal_ticks_ms() + duration;
383392
music_data->async_loop = false;
384393
music_data->async_notes_len = 0;

0 commit comments

Comments
 (0)