我目前有这段有效的代码。我有两个问题。
- 如何将目录设置为“支持文件”?
- 如何在文件名中使用变量?我需要它根据变量提取任何动物的 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/