4

So I'm trying to test out the audio player on the iPhone, and I went off Troy Brant's iOS book. I have the Core Audio, Core Foundation, AudioToolbox, and AVFoundation frameworks added to my project. The error message I get is in the subject field. I read like 20 pages of Google search results before resorting to asking here! /sigh. Thanks if you can help. Here's my code, pretty much verbatim out of his book:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Yonah" ofType:@"caf"];
NSLog(@"%@", soundFilePath);
NSURL *fileURL = [NSURL URLWithString:soundFilePath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];

if (!error)
{
    audioPlayer.delegate = self;
    //audioPlayer.numberOfLoops = -1;
    [audioPlayer play];
}
else
{
    NSLog(@"Error loading audio clip: %@", [error localizedDescription]);
}    

EDIT: Holy Shinto. I figured out what it was. I changed

NSURL *fileURL = [NSURL URLWithString:soundFilePath];

to

NSURL *fileURL = [NSURL fileURLWithPath:soundFilePath];

to the latter and I was getting a weird error, weirder than the one in the subject BUT I googled that and I changed my OS input device from my webcam to my internal microphone and guess what, it worked under the fileURLWithPath method. I'll be. Damned.

Kjuly
  • 34,476
  • 22
  • 104
  • 118
neptune
  • 63
  • 5
  • .caf should be supported in iOS5 but maybe you should try with mp3 or something. you did remember to import your Jonah.caf in the project? Also: why are you setting the delegate - do you need it? Do you get the same error if you just call [audioPlayer prepareToPlay]; instead of [audioPlayer play];? – Rok Jarc Jan 26 '12 at 16:46

2 Answers2

2

try this one- convert your url into NSdata

NSString* resourcePath = self.audioStr; //your url
 NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
 NSError *error = [[NSError alloc] init];

NSLog(@"url is %@",resourcePath);

audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData  error:&error];
audioPlayer.numberOfLoops = 0;

if (error)
{
    NSLog(@"Error in audioPlayer: %@",
          [error localizedDescription]);
} else {
    audioPlayer.delegate = self;
    [audioPlayer prepareToPlay];
}`
Kanhaiya Sharma
  • 1,040
  • 8
  • 20
0

Try to read the audio file with something like this:

audioPlayer_ = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:[NSString stringWithString:soundFilePath_]] 
error:&error];
nano
  • 2,511
  • 4
  • 25
  • 42