URLWithString 对于资源路径返回 nil - iphone
由于某种原因获取资源的 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
音频 URL:0
错误错误域=NSOSStatusErrorDomain 代码=-50“操作无法完成。(OSStatus 错误 -50。)”
Having a problem getting the URL for a resource for some reason: This code is in viewDidLoad, and it's worked in other applications, but not here for some reason:
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);
LOG OUTPUT:
AUDIO STRING: /var/mobile/Applications/D9FA0569-45FF-4287-8448-7EA21E92EADC/SoundApp.app/sound.wav
AUDIO URL: 0
Error Error Domain=NSOSStatusErrorDomain Code=-50 "Operation could not be completed. (OSStatus error -50.)"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的字符串没有协议,因此它是无效的 url。试试这个...
Your string has no protocol, so it's an invalid url. Try this...
只需将一行更改为:
Just change one line to this:
您在
NSLog
方法中将audioURL
作为%d
传递,因此您得到 0。如果您将其作为对象传递给%@
你会得到NULL
。尝试像这样传递到音频播放器并跳过字符串。
You're passing
audioURL
in yourNSLog
method as%d
hence why you get 0. If you pass it as an object with%@
you'll getNULL
.Try passing into the audioplayer like this and skip the string.
您没有足够仔细地阅读响应 - 您正在使用 URLWithString,而您应该使用 fileURLWithPath。您无法将 file:// 路径传递给 URLWithString。我认为您还需要在字符串前面添加 file:// ,因为您只有一个路径(正如指出的那样没有协议)。
You aren't reading the responses carefully enough - you are using URLWithString, when you should use fileURLWithPath. You can't pass a file:// path to URLWithString. I think you also need to prepend file:// at the front of the string as you have only a path (which as pointed out has no protocol).