Michael Michael - 6 months ago 22
Objective-C Question

Audio overlapping in Xcode

I've done a lot of reading and research in trying to come up with a solution to my problem and can't seem to make my code work the way I want, or the way it should. What I want to do is be able to have different buttons play different, short sounds, without overlapping each other if I decide to click another sound button before another sound button's audio is finished. I've successfully got to the point where they play their designated sound using

, but they still overlap when I click on multiple

Below is a sample of my code:

Interface file:

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

@interface ViewController : UIViewController {



Implementation file:

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

@implementation ViewController : UIViewController

- (IBAction)Sound:(id)sender
NSString *path = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];

- (void)viewDidLoad
[super viewDidLoad];

- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];


I would appreciate the help more than you know, as I've spent quite some time trying to get it to work the way it should. If you have any questions for me please let me know! Thank you very much.



I have the understanding that when you play an AudioSystemSound that it will play until completion. This method of playing Audio isn't a highly functional one and only really supposed to be used for simple "clicks" and "dings" etc. For a more comprehensive audio suite of features perhaps you could look at using the AVFoundation library with AVAudioPlayer where you can call "stop" to cease playing the called sound.


Edited addition to the above answer:

In your .h file make sure you include;

@import AVFoundation;

and then create an AV player with;

AVAudioPlayer *playAudio

In your .m file add this block of code below in your method that needs to play the sound. Of course adjust the song/audiofile name and format appropriately;

NSString *backgroundMusic = [[NSBundle mainBundle]
                             pathForResource:@"insertSongNameHere" ofType:@"mp3"];

playAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:insertSongNameHere] error:NULL];
playAudio.numberOfLoops = -1;
[playAudio play];

Note: Number of loops being -1 means repeat forever. You can of course make that whatever number you like though. I hope that all helps, if not let me know and I'll see what I can do to assist!