0
$\begingroup$

I'm trying to imitate the way that piano makes a sound and I create a DynamicModule to be the key like the following code:

DynamicModule[{col = Green}, 
 EventHandler[
  Dynamic[Graphics[{col, 
     Polygon[{{0, 0}, {1, 0}, {1, 3}, {0.5, 3}, {0.5, 5}, {0, 5}}]}, 
    ImageSize -> 
     Tiny]], {"MouseDown" :> {(col = 
       col /. {Red -> Green, Green -> Red}), 
     EmitSound[Play[(1 - t)*Sin[440 2 Pi t], {t, 0, 1}]]}},
  {"MouseUp" :> {(col = col /. {Red -> Green, Green -> Red})}}]]

Now it can change color when I press it and play the certain sound. But I want to get it more realistic by starting to weaken the sound that is playing when I release my mouse.How can I do this? Or is there any other methods that can get similar result?

$\endgroup$

1 Answer 1

1
$\begingroup$

You can use SoundNote that already sounds as piano (or other instrument) and on mouse up you can play any sound of duration 0 and volume 0 that stops the previous sound.

DynamicModule[{col = Green}, 
 EventHandler[
  Dynamic[Graphics[{col, 
     Polygon[{{0, 0}, {1, 0}, {1, 3}, {0.5, 3}, {0.5, 5}, {0, 5}}]}, 
    ImageSize -> 
     Tiny]], {"MouseDown" :> {(col = 
       col /. {Red -> Green, Green -> Red}), 
     EmitSound[
      Sound[SoundNote[0], 5]]}}, {"MouseUp" :> {(col = 
       col /. {Red -> Green, Green -> Red}), 
     EmitSound[Sound[SoundNote[0], 0, SoundVolume -> 0]]}}]]
$\endgroup$
2
  • $\begingroup$ Thanks for answering. I tried the method just now but it didn't work as I want. I changed the volume and duration of the soundnote, finding that two sound were played at the same time. $\endgroup$ Commented Dec 7, 2023 at 2:20
  • $\begingroup$ Oh, I got it. Maybe the function Play is different with Sound in the EmitSound. It works when I use Sound both as you did. $\endgroup$ Commented Dec 7, 2023 at 7:19

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.