I posted this answer earlier, and it received 2 upvotes, but then I changed my mind, deleted it, did some more troubleshooting, so now I am reposting it.
First of all, duration
is not a global variable; it is a member of your class.
Now, I really do not know why duration
is zero when it is passed to PlayMusic()
. I looked into it hard, and there appears to be no reason for such a thing happening. I thought that panel1_MouseDown()
sets it to zero, and immediately afterwards panel1_Click()
passes it to PlayMusic()
, but that is not correct: Click()
occurs together with MouseUp()
, so duration
should not have been zero at that time.
But it does not matter, because your approach is completely wrong, so you are going to have to change it anyway, and the problem will probably fix itself in the process.
You will never be able to invoke PlayMusic()
with pitch and duration, because you need to invoke PlayMusic()
immediately upon MouseDown()
, but at that time you do not know what the duration is going to be yet.
Also, using a timer to figure the duration is entirely unnecessary, and inherently inaccurate; if you really need to know the duration, just record the current time on MouseDown()
and subtract it from the current time on MouseUp()
. But you do not need to do that, either. All you need to do is just stop playing the sound on MouseUp()
. (You will only have to do it in order to be able to replay the sound later, if you so wish.)
Also, I would advise you to seriously reconsider the correctness of adding new MouseDown and MouseUp event handlers to the panel every time you receive an OnClick event.
Also, I would advise you to use meaningful variable names, especially when you are showing your code to others, asking them to figure out what is wrong with it. Your panel1_OnClick handler does not handle click events for panel1, as it name would suggest, but instead it handles click events for all your music key buttons.