0

I'm trying to play a mp3 file using AVFoundation framework. It can't detect the file and has the following error:

     Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

Code implemented:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
NSLog(@"directory %@",path);
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];

When I change the pathForResource:@"sound" to pathForResource:@"sound " (the space ) it can detect the file but no sound heard. I have declared the AVdelegate in the .h file too. Anyone knows whats the problem?

DesperateLearner
  • 1,115
  • 3
  • 19
  • 45
  • Is your device muted? This comes up more than you'd think. – Mick MacCallum Sep 19 '12 at 17:04
  • http://stackoverflow.com/questions/4640880/mp3-playing-using-avaudioplayer-not-working-on-device http://stackoverflow.com/questions/8016765/avaudioplayer-not-playing-any-sound?rq=1 these two links sorted the issue. sill appreciate it – DesperateLearner Sep 19 '12 at 17:36

1 Answers1

0

You need to gige prepareToPlay first for the audio to play.. check this code snippet.. it works for me.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", fileName]];

NSError        *err;

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{    
    AVAudioPlayer  *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
              [NSURL fileURLWithPath:filePath] error:&err];

    player.delegate = self;

    [player prepareToPlay];
    [player setNumberOfLoops:0];
    [player setVolume:0.5];
    [player play];    

}

cancerian
  • 942
  • 1
  • 10
  • 18
  • `prepareToPlay` is helpful for decreasing the amount of time it takes for the sound to start playing but is not actually necessary. Additionally the OP is having trouble playing a sound out of the application bundle, not `NSDocumentDirectory`. Maybe you could edit this to help OP with that :) – Mick MacCallum Sep 19 '12 at 17:09
  • Hello NSPostWhenldle what do u mean by OP? – DesperateLearner Sep 19 '12 at 17:12