7

由于某种原因在获取资源的 URL 时遇到问题:此代码在 viewDidLoad 中,并且在其他应用程序中也可以使用,但由于某种原因不在此处:

NSString* audioString = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"];
NSLog(@"AUDIO STRING: %@" , audioString);

NSURL* audioURL = [NSURL URLWithString:audioString];
NSLog(@"AUDIO URL: %d" , audioURL);

NSError* playererror;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&playererror];
[audioPlayer prepareToPlay];    

NSLog(@"Error %@", playererror);

日志输出:

音频字符串:/var/mobile/Applications/D9FA0569-45FF-4287-8448-7EA21E92EADC/SoundApp.app/sound.wav

音频网址:0

错误 错误域 = NSOSStatusErrorDomain 代码 = -50 “操作无法完成。(OSStatus 错误 -50。)”

4

4 回答 4

22

您的字符串没有协议,因此它是无效的url。试试这个...

NSString* expandedPath = [audioString stringByExpandingTildeInPath];
NSURL* audioUrl = [NSURL fileURLWithPath:expandedPath];
于 2010-01-21T21:51:34.240 回答
6

只需将一行更改为:

    NSURL* audioURL = [NSURL fileURLWithPath:audioString];
于 2010-01-21T22:15:30.727 回答
4

你传入audioURL你的NSLog方法,%d因此你得到 0。如果你把它作为一个对象传递,%@你会得到NULL.

尝试像这样传递到音频播放器并跳过字符串。

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]];
于 2010-01-21T21:42:01.577 回答
2

您没有足够仔细地阅读响应 - 您正在使用 URLWithString,而您应该使用 fileURLWithPath。您不能将 file:// 路径传递给 URLWithString。我认为你还需要在字符串前面加上 file://,因为你只有一个路径(正如所指出的没有协议)。

于 2010-01-21T22:19:00.203 回答