我正在使用大约50个AVAudioPlayers,每个都加载一个单独的音频文件。文件已修复并位于应用程序包中。它们是由应用程序中的事件触发的。目前我正在硬编码每个播放器实例的创建,如下所示:
//No01
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"audio1" ofType:@"aiff"]];
self.no01Player = [[AVAudioPlayer alloc] initWithContentsOfURL:no01URL error:nil];
no01Player.numberOfLoops = 0;
no01Player.volume = 0;
no01Player.delegate = self;
//No02
NSURL *no02URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"audio2" ofType:@"aiff"]];
self.no02Player = [[AVAudioPlayer alloc] initWithContentsOfURL:no02URL error:nil];
no02Player.numberOfLoops = 0;
no02Player.volume = 0;
no02Player.delegate = self;
//No03 and so on...
显然这是一个非常繁琐且编码不好的做法。我希望在Plist中包含文件列表,并将这些文件加载到仅填充上述代码的一个示例的变量中。我想学习如何干这个,但是从Plists,数组,词典等加载数据的经验有限。
感谢任何帮助,即使是指向相关教程的方向。
谢谢。
答案 0 :(得分:4)
您只需使用“新行”分隔符将音频文件名放在文本文件中即可。并读取文件并将名称存储在数组中。要创建URL,请从数组中动态获取文件名,如下所示
// Read description from text file
NSBundle *audioBundle = [NSBundle mainBundle];
NSString *audioPath = [audioBundle pathForResource:audioFileNames ofType:@"txt"];
NSString *audioContent = [NSString stringWithContentsOfFile:audioPath encoding:NSUTF8StringEncoding error:nil];
// ===========Make an array using audioContent=============
NSArray *audioFiles = [audioContent componentsSeparatedByString:@"\n"];
使用数组获取文件名:
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[audioFiles objectAtIndex:audioCount]] ofType:@"aiff"]];
如果你的文件名是audio1,audio2 ..不需要使用所有这些。只需更改网址,如:
NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"audio%d",audioCount] ofType:@"aiff"]];
答案 1 :(得分:1)
对于其他需要这样做的人来说,这是我最终的结果:
//Load location data from Plist file into an Array
NSString *path = [[NSBundle mainBundle] pathForResource:@"Audionodes" ofType:@"plist"];
locationArray = [[NSArray alloc] initWithContentsOfFile:path];
// Create AVAudioPlayers for this view
self.audioPlayerArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [locationArray count]; i++) {
NSString *filename = [[locationArray objectAtIndex:i] valueForKey:@"filename"];
NSString *filetype = [[locationArray objectAtIndex:i] valueForKey:@"filetype"];
int loops = [[[locationArray objectAtIndex:i] valueForKey:@"loops"] intValue];
NSURL *url = [[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:filename ofType:filetype]];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.delegate = self;
player.numberOfLoops = loops;
player.volume = 0;
[self.audioPlayerArray addObject:player];
[url release];
[player release];
}
将生成的玩家放入audioPlayerArray意味着我可以在以后找到它们。