Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How would I create a button that can play an audio file

I want to make a button that when clicked, it will play a 1.5 second sound clip.

I have imported AVFoundation into my View Controller. Also ive put the audio files into my project, and renamed them cSound.wav, gSound.wav... ect.

I couldn't find a good tutorial on this seemingly simple task. Thanks for your help

3 Answers

For this task you will need to hold on to an instance of a AVAudioPlayer in your ViewController. You should get the path where you have added the sound file. It should be in your main app bundle. Also don't forget to hook up the button in your IB.

-(IBAction)soundFileButtonClicked:(id)sender {
    NSString* bundleDirectory = (NSString*)[[NSBundle mainBundle] bundlePath];

    NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:@"cSound.wav"]];
      self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
      [self.audioPlayer play]
}

i ended up doing it like

 static var gSoundPlayer:AVAudioPlayer = AVAudioPlayer()

    func soundG() {
        do {
            let gSoundPath = Bundle.main.path(forResource: "g", ofType: "wav")
            try Sounds.gSoundPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: gSoundPath!) as URL)
            Sounds.gSoundPlayer.play()
        } catch {} }

then setting a button action to play the function in a view controller

Hi Justin,

If you're using Swift, you may want to check out the Treehouse course titled Build an Interactive Story App with Swift 3. The last section is all about adding sound effects, and will teach you the basics. Feel free to poke around in the lessons to just figure this part out, or take the whole course.

Cheers :beers:

-Greg