AVAudioFile无法从文档目录

时间:2016-04-21 15:31:38

标签: ios objective-c avaudioengine avaudioplayernode avaudiofile

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/audio.mp3",documentsDirectory];
NSURL *audioPathURL = [NSURL fileURLWithPath:filePath];
NSFileManager *filemanager = [[NSFileManager alloc]init];
    if ([filemanager fileExistsAtPath:filePath])
    {
AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:audioPathURL error:&err];
}

这无法读取音频文件,它返回audioFile nil。当我从NSBundle传递url时,对于相同的代码,如

NSString *path  = [[NSBundle mainBundle] pathForResource:@"Audio" ofType:@"mp3"];
NSURL *pathURL = [NSURL fileURLWithPath : path]; 

它工作正常,任何sugestions。谢谢

2 个答案:

答案 0 :(得分:0)

问题可能是您用于将文件名附加到路径的“/”。请尝试以下更改

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

或尝试以下替代方案:

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"audio.mp3"];

答案 1 :(得分:0)

NSBundle类用于在应用程序包中查找事物,但Documents目录在bundle之外,因此生成路径的方式不适用于Documents目录。

尝试如下:

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"audio.mp3"];

NSURL *audioPathURL = [NSURL fileURLWithPath:filePath];
NSFileManager *filemanager = [[NSFileManager alloc]init];

if ([filemanager fileExistsAtPath:filePath])
{
      AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:audioPathURL error:&err];
}