View Full Version : Creating a Button that plays a sound file.
Jul 13, 2008, 12:36 PM
I am trying to create a button that, when clicked, it plays a given sound file in the app's filesystem.
This is what I have set up thus far:
Regular Rectangular button -> connected to NSObject Called "sounds" -> with the Event "playsound1" chosen as the event.
I then wrote the class files, brought them into Xcode file project under classes, and now I'm staring at sound.h and sounds.m with no idea what to do next.
I was able to create in a regular Mac OSX Cocoa, a button that plays the system beep using NSBeep. However, I don't know how to achieve this similar objective with using a given sound file in the iPhone Cocoa Touch.
Jul 13, 2008, 01:30 PM
I found this on the iPhone Dev Site:
AudioServicesCreateSystemSoundID (fileURL, soundID)
where would I put this in my code.
Jul 13, 2008, 08:51 PM
But... I really need help. I'm so confused. I've spent hours searching almost every search engine and forum I could find. I have a similar topic posted on 4 different forums and have recieved no replies.
Jul 13, 2008, 09:17 PM
Buttons only perform "actions". A button will never "play a sound". A button will perform an action--which will be a method. The method may only play a sound and finish, or the method could play a sound and do something else.
Normally, that method will be in the same class as your button, but sometimes not. The class where the method exists is called the "Target".
Therefore, you need to apply the method [addTarget:action:forControlEvents:] to every button you want to run custom methods.
You tell it WHERE the method is, the @selector that points to the method, and for which even you want to trigger the action. Often, this is UIControlEventTouchUpInside. But it could be any of several UIControlEvents. You can [addTarget:action:forControlEvents:] as many times as you want for a single button. You can also OR together UIControlEvents to make one action happen for lots of events.
Normally, you would play a sound with AudioServicesCreateSystemSoundID (see above) as part of your method/action. You might play the sound first-thing in the method, then do other things.
You could add several selectors for different events--one that plays the sound on UIControlEventTouchDownInside (play a sound when you start to touch a button) and one that processes some data in your application on UIControlEventTouchUpInside (actually do something when you finish touching the button).
This is fairly well documented in the iPhone section of the XCode documentation. Basically every example that Apple provides gives lots of examples of implementing buttons. Several examples provided by Apple plays simple sounds. Look for any with an Audio folder in the project folder.