3

This is my code right now. I am trying to add sound effects when a button is pressed.

#import <AudioToolbox/AudioToolbox.h>

- (void)threeBombExplosion
{
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
    NSURL *threeExplosionsURL = [NSURL fileURLWithPath:soundPath];
    AudioServicesCreateSystemSoundID(CFBridgingRetain(threeExplosionsURL),&_threeExplosionsID);

}

and I am calling this on the function I want it to be executed (UIButton Action).

AudioServicesPlaySystemSound(_threeExplosionsID);
Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
romansito
  • 33
  • 1
  • 6
  • 3
    Possible duplicate of [How can I add sound to a button in iOS?](http://stackoverflow.com/questions/11888059/how-can-i-add-sound-to-a-button-in-ios) – Teja Nandamuri Dec 21 '15 at 18:43

1 Answers1

5

Firstly, thats not how you should be calling your mp3 file, you should be using the av audio player object.

NSString *path = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

Make sure you have strong reference to it, otherwise it might get removed in memory

@property (strong,nonatomic) AVAudioPlayer *audioPlayer;

I would check that the method is being called when the button is being pressed. If you have a touchupinside action, then your method will be:

-(IBAction)buttonPressed {
    [self threeBombExplosion];
}

If that is not working, you should check that the resource is being added to your project, in Xcode you need to make sure you have added it.

enter image description here

In my project i created a subfolder called resources and then an additional one called sounds and placed it neatly in there.

Reedy
  • 1,866
  • 2
  • 20
  • 23
  • Not sure that "you should be using the AV Audio Player", Audio Services system sounds work very well for simple purposes like this one. – jcaron Dec 22 '15 at 08:30
  • The sounds he is trying to play are not system sounds, they are game sounds. – Reedy Dec 22 '15 at 10:11