0

I have always used audio toolbox to play my sounds, but users have saying there is no sound, this is because when you are on silent it doesnt play. I have tried many times to swap instead to av foundation but it never works for me. this is the code i am attempting to use now:

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

[theAudio play];}
rexr
  • 89
  • 11

1 Answers1

3

Reason could be that in ARC your audio player is being released by ARC, therefore you need to make a strong reference of the AVAudioPlayer, you can do that by making the AVAudioPlayer as class level property. here is how you do it, in your .h file like this

@property (strong, nonatomic) AVAudioPlayer *theAudio;

and in .m file synthesize it like this

@synthesize theAudio;

and finally your code would look like this

- (IBAction)soundbutton:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"EASPORTS" ofType:@"mp3"];
    self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[self.theAudio play];
}

check also if your delegate methods are responding something

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error;
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
  • well if it is not your project then how come you know the code? you should anyways make the player as a property in the class, it will solve your problem – nsgulliver Feb 28 '13 at 20:27
  • but try to make the `AVAudioPlayer` as property in the class as i mentioned – nsgulliver Feb 28 '13 at 20:48
  • still nothing plays :( when i go back to my old code it works :/ : - (IBAction)soundbutton:(id)sender { CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef soundFileURLRef; soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"EASPORTS", CFSTR ("mp3"), NULL); UInt32 soundID; AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); AudioServicesPlaySystemSound(soundID); } – rexr Feb 28 '13 at 20:48
  • according to your question, the answer is presented and otherwise I don't know what could be the problem in your code unless I see the code of your project related to `AVAudiPlayer` – nsgulliver Feb 28 '13 at 22:11
  • code in the answer is the working code for solution for the problem and symptoms presented, if you don't know how to play audio then you should first learn how to play audio using AVFoundation. there are number of tutorials over internet you can find – nsgulliver Mar 01 '13 at 15:12