1

我正在使用大约 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、数组、字典等加载数据的经验有限。

任何帮助表示赞赏,即使它是指向我相关教程的方向。

谢谢你。

4

2 回答 2

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.. 不需要使用所有这些。只需更改 URL,例如:

NSURL *no01URL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"audio%d",audioCount] ofType:@"aiff"]];  
于 2012-12-04T05:15:54.967 回答
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 中意味着我可以稍后再使用它们。

于 2012-12-31T00:21:18.910 回答