I have the following Mathematica animation:

Animate[Plot[k*x^2, {x, -2, 2}, 
  PlotRange -> {{-2, 2}, {-10, 10}}], {k, -2, 2, 0.1}]

I also have a sound file in the same Mathematica file, which is A VERY SHORT music clip, in "wav" format. The clip is about 32 seconds long. Now I want to integrate this sound file into the above animation:

The following command will do the job, but it will make the animation WAY TOO sluggish, and almost useless:

Animate[Plot[k*x^2, {x, -2, 2}, PlotRange -> {{-2, 2}, {-10, 10}}, 
  Epilog -> {EmitSound[snd]}], {k, -2, 2, 0.1}]

Could you please suugest a better way of doing it? Thank you very much!

  • $\begingroup$ How long is the .wav file? Do you need it to play continuously during animation or only at the beginning/end ? $\endgroup$ – Vitaliy Kaurov Sep 9 '12 at 3:47

This is one way to control the sound emission. Import a short .WAV file:

sound = Import[ "ExampleData/rule30.wav" ]

enter image description here

Now make sound only when your animation control reaches some value - k=0 or k=1 in this case:

Animate[If[k == 0 || k == 1, EmitSound[sound]];
 Plot[k*x^2, {x, -2, 2}, PlotRange -> {{-2, 2}, {-10, 10}}],
 {k, -2, 2, 0.1, AnimationRate -> 1, AnimationRunning -> False}]

enter image description here

  • $\begingroup$ Dear Mr. Vitaliy Kaurov, Thank you very much for your help. It works. I still have a question related to your answer. I will ask you later. I was slightly confused about the use of semicolon (;) after the EmitSound[sound]] command, and all that is included within the Animate command. I have never used such within an Animate command. I will try to understand it myself - if not perhaps I can ask you again. Still, thank you so much! Tim – $\endgroup$ – Tim Sep 9 '12 at 5:31
  • 3
    $\begingroup$ PS: You had asked how long is the wav file. Mine was about 32 seconds long. Using your method, it plays again and again without a problem. A second question is that can I cut off the music for certain values of k, and again restart it when k equals the previous values? I was just wondering. What is the Mathematica command to make a sound silent, in other words? Thanks in advance $\endgroup$ – Tim Sep 9 '12 at 5:34
  • $\begingroup$ @Tim , I will ponder about your question a bit. Meanwhile it maybe worth posting it as a separate question. Because it is a good question and also maybe someone already knows the answer. $\endgroup$ – Vitaliy Kaurov Sep 9 '12 at 6:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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