Reputation: 187
I've looked at a lot of answers on here for this question and can't get any to work.
Here is my issue, I'm trying to play a sound on a button press, here is where the file is located
Here is my code
- (void)playSoundWithOfThisFile:(NSString*)fileName {
NSString *soundFilePath = [NSString stringWithFormat:fileName,
[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:nil];
player.numberOfLoops = 1;
[player play];
}
When I run through the code the values are as follows
fileName = Mummy.mp3
`soundFilePath = Mummy.mp3` (I've had it Sounds/Mummy.mp3 and this doesn't work either)
soundFileURL = Mummy.mp3
-- file:///
player = nil
Any help would be greatly appreciated. The error if I catch it is just a generic error with no info
Upvotes: 3
Views: 2497
Reputation: 11127
Try to use the below code
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:@"test" ofType:@"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], & soundID);
AudioServicesPlaySystemSound(soundID);
Don't forget to import
#import <AudioToolbox/AudioToolbox.h>
Upvotes: 5
Reputation: 141
NSString *path = [[NSBundle mainBundle] pathForResource: @"how_to_play" ofType: @"mp3"];
if(!self.theAudio)
{
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
self.theAudio.delegate = self;
[self.theAudio play];
}
put in viewcontroller.h
< AVAudioPlayerDelegate>
@property(nonatomic,strong) AVAudioPlayer *theAudio;
Upvotes: 1
Reputation: 1754
Try this.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Mummy" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:filePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:nil];
player.numberOfLoops = 1;
[player play];
Docs on pathForResource: ofType:
Upvotes: 1