6
$\begingroup$

I have created a sound which I would like to play continuously until stopped, by looping back to the beginning. The sound is represented as list of samples, which can be played by

EmitSound[Sound[SampledSoundList[list, rate]]]

or

ListPlay[list, SampleRate -> rate]

Any suggestions?

$\endgroup$
1
  • $\begingroup$ If you know the duration, and you should, then: break = True; Button["Stop", break = False] While[break, EmitSound[Sound[SoundNote[]]]; Pause[1]] may be useful. Does it work for you? $\endgroup$
    – Kuba
    Feb 12, 2015 at 13:23

2 Answers 2

4
$\begingroup$

Here is a way of doing a sound loop with a scheduled task. The task is started and stopped with a Toggler that looks like a play/pause button.

sound = Play[(2 t) Sin[2 Pi 2000 t], {t, 0, 1}];
DynamicModule[{state = "pause"},
  Grid[{{
    Toggler[Dynamic @ state,
      {"pause" -> Style["\[RightPointer]", 24], 
       "play" -> Style["\[FilledSmallSquare]", 16]}],
    Dynamic @
      If[state == "play",
        If[ScheduledTasks[] == {}, RunScheduledTask[EmitSound[sound]]]; "playing",
        If[ScheduledTasks[] != {}, RemoveScheduledTask[ScheduledTasks[]]]; "paused"]}}]]

It starts off paused, looking like

paused

Clicking on the right facing triangle starts the sound loop and the Toggler changes to black square, so while the sound is playing, the display looks like

playing

Clicking on square stops the sound loop.

$\endgroup$
2
$\begingroup$

The short code

run = True; Button["stop", run = False]
While[True, Print[run]; Pause[1]; If[! run, Break[]]]

prints the value of run as long as it is True. Clicking the Button labeled stop sets run to False and terminates the loop. Replacing Print[run]; Pause[1] by code to play the tones should behave the same.

run = True; Button["stop", run = False]
While[True, ListPlay[list, SampleRate -> rate]; If[! run, Break[]]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.