Sound play button toggle on off

Hi All

How do I get a button/object to toggle a sound playing. Ie if i have an image well that on mouse down i want to play a sound but stop if its already playing. I cant seem to get it to work. Heres my code:

[code] Dim f as FolderItem = GetFolderItem(“1.mp3”)
If f <> nil then
Dim s as Sound = f.OpenAsSound

If s.IsPlaying then
  s.Stop
Else
  s.Play
End if

Else
//user cancelled
End if[/code]

If i press the image well then sound plays fine, but doesnt stop if i press it again. It just triggers another sound. Any help appreciated.

sorry. Should have also said this is fired on mousedown event of image well

Since you dim s as sound each time the button is clicked, you are getting a new sound object each time. If you want to keep track of a sound currently playing, move the scope of your sound object (s) to the window or maybe even the project level.

Okay.I obviously need to know about scope. No idea… thanks

But sureley the if… else loop checks if its playing anyway or am i miles off ?

Each time the event is raised, you’re creating a new instance of the sound (Dim s as Sound = f.OpenAsSound). This means than s.IsPlaying is always False.

Make s As Sound a property of the window (giving it a wider scope than Dim’ing it within the event) and then:

    If s = Nil Then ' s is a property of the window
       s = f.OpenAsSound ' instantiate the s only if needed
    End If
    If s.IsPlaying then
      s.Stop
    Else
      s.Play
    End if

Andrew did a good job but let me just add a couple of things. Firstly, the concept of scope is essential to all programming languages. You would be wise to read up on it from the Xojo docs and whatever you can find on the web.
Secondly, something that may confuse you. The system plays sounds asyncronously. Therefore, once you start that sound playing with s.Play it will continue to play. But once your event exits, you have no reference to that sound. You couldn’t stop it if you wanted to. If you are certain that your window will not be closed while the sound is playing, then making s a property of the window will work. Otherwise, you may want to dim s in a module of global scope or, if you have other sounds to deal with, create a custom class to handle your sounds and dim a global instance.
Now, the only thing within your button event is
If s.IsPlaying then
s.Stop
Else
s.Play
End if

Bing…lightbulb moment. Of course. I think i get it. Cheers for you help Roger and Andrew. Much appreciated.