Reputation: 385
I am new to iOS and trying to add sound to my app. I have followed several tutorials about adding a simple sound file to my project, but ALL with the same result. I get no errors, but no sound plays. Any ideas on what I am doing wrong? Any help would be appreciated!
- (IBAction)playSound:(id)sender {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(soundFilePath);
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
player.numberOfLoops = 1;
[player play];
}
**UPDATE***
So I never had any luck with the above code which is very discouraging, but I did end up getting it to work using the AudioToolbox Framework instead, using this:
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:@"test" ofType:@"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], & soundID);
AudioServicesPlaySystemSound(soundID);
Can anyone explain to me the difference, why this one works and the other does not?? I am curious more than anything. Would love some clarification.
Upvotes: 3
Views: 7782
Reputation: 27
Make sure you install quartz.h, or a specific framework that supports audio players. Just double check.
Had the same problem a while back and the framework must be installed properly.
Upvotes: 0
Reputation: 385
Finally figured it out. I needed to create a property for AVAudioPlayer in my header file in order to get it to work. Here is what I did:
// .h file
@interface ThirdViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (void) playSound //method in .m file
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test"
ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer play];
}
Upvotes: 9
Reputation: 12233
Simplify your code by doing the follow. Also drop your test.mp3 to the root of your project directory in xcode. Your mp3 placement and location is very important. Also ensure volume is up, and vibrate is off of your device, and it's unmuted.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test"
ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
[audioPlayer play];
Upvotes: 0