iphone - iOS:NSUrl 语法

标签 iphone objective-c ios nsurl

我目前有这段有效的代码。我有两个问题。

  1. 如何将目录设置为“支持文件”?
  2. 如何在文件名中使用变量?我需要它根据变量提取任何动物的 mp3。
- (void)playAnimal{    
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Sheep.mp3", [[NSBundle mainBundle] resourcePath]]];        
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;        
    if (audioPlayer == nil)
        NSLog([error description]);
    else
        [audioPlayer play]; 
}

我是 Objective-C 的新手,所以很多语法和一般方法对我来说都是新的。谢谢你的耐心!

最佳答案

使用以下内容:

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

当您的资源被复制到包中时,它们不会保留它们的目录结构。只需按名称标识资源,它就会找到它的路径。

仅供引用,以下内容也有效:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Sheep.mp3" ofType:@""]];
NSURL *url = [NSURL fileURLWithPath:path];

如果您有一组资源在逻辑上组合在一个 plist 中并且您正在以编程方式读出它们,这可能很有用。例如:

//  reference to a dictionary with the entry 'Sheep.mp3'
NSString *resourceName = [dictionary objectForKey:item1]; 
NSString *path = [[NSBundle mainBundle] pathForResource:resourceName ofType:@""]];
NSURL *url = [NSURL fileURLWithPath:path];

关于iphone - iOS:NSUrl 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9084831/

相关文章:

objective-c - 有没有办法在 Cocoa 中更改用户桌面目录路径值?

ios - 如何在不使用 segue 的情况下传递数据

ios - iOS 中 UITouch 时间戳的精度是多少?

ios - 为什么我的应用程序文档文件夹不可见?

iphone - iOS:链接第三方框架并在部署时崩溃

objective-c - 如何为附加到 UIImageView 的 CALayer 设置动画?

objective-c - Cocoa 同时多次加载 Nib 模板

ios - 聚光灯搜索后显示 View Controller

iphone - iPad 和 MapKit - 无法拖动可拖动标记

ios - UIPrintInteractionController 未在 iPad 中显示