AVFoundation - iOS无法听到声音

时间:2012-09-19 15:49:25

标签: ios xcode audio avfoundation

我正在尝试使用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。谁知道这个问题是什么?

1 个答案:

答案 0 :(得分:0)

首先需要gige prepareToPlay才能播放音频..请查看此代码段..它适用于我。

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

}