0

我正在尝试使用 AVFoundation 框架播放 mp3 文件。它无法检测到文件并出现以下错误:

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

实现的代码:

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];

当我将 pathForResource:@"sound" 更改为 pathForResource:@"sound" (空格)时,它可以检测到文件但听不到声音。我也在 .h 文件中声明了 AVdelegate。有谁知道是什么问题?

4

1 回答 1

0

你需要先准备好准备播放音频才能播放..检查这个代码片段..它对我有用。

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];    

}

于 2012-09-19T17:05:49.847 回答