Peter V
Peter V

Reputation: 2488

Play custom sound when storyboard button tapped

I made custom buttons inside of a .storyboard that need to play a sound when tapped (not a soundboard, just play a custom audio file of a button press).
Is there a sound option in the storyboard editor that would enable this? If not, how else can this be achieved?

Upvotes: 1

Views: 2208

Answers (2)

user3474377
user3474377

Reputation: 21

The above code worked when I set the volume using

[player setVolume:1.0];

It was not working till I did that.

Upvotes: 2

YDL
YDL

Reputation: 714

The storyboard doesn't allow you to assign a 'audio' to a button. What you can do however is use the fairly simple AVAudioPlayer in a function;

Add Libraries

To use the AVAudioPlayer you will first need to add 2 libraries/frameworks to your project. These Frameworks contains the basecode for the actual player and allows us (the app writers) to use it.

Select your project in xCode and go to Build Phases. Select Link Binary with Libraries. Press the little [+]-icon and add the frameworks:

  • AudioToolbox
  • AVFoundation

Frameworks

Now we have to tell our code we will actually be using these two frameworks. Open the .H file of your controller and, at the top, add:

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

Event + Player

Bind one of the events of a UIButton (via the storyboard), eg Touch Up Inside, to a new IBAction function (eg playSound).

By binding the event, your telling your application that if the users presses a button -> run this function/code.

Now, within your newly created IBAction function (eg playSound) add some code to create a player with an MP3 and play it;

- (IBAction)playSound:(id)sender
{

   // Load in a audio file from your bundle (all the files you have added to your app)
   NSString *audioFile = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"mp3"];

   // Convert string to NSURL
   NSURL *audioURL = [NSURL fileURLWithPath:audioFile];

   // Initialize a audio player with the URL (the mp3)
   AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];

   // Start playing
   [player play];

}

I hope this will help you along in the right direction?

Check the doc of Apple for al the functions/methods the AVAudioPlayer has got besides "play" (eg buffering, pause etc)

Upvotes: 5

Related Questions