使用AVAudioPlayer播放多个音频文件

inS*_*t09 7 iphone audio avaudioplayer

我打算免费发布我的10首歌曲录音,但是捆绑在一个iPhone应用程序中.它们不适用于网络或iTunes,也不适用于现在的任何地方.

我是iphone sdk(最新)的新手,你可以想象,所以我一直在浏览开发者文档,各种论坛和stackoverflow来学习.

Apple的avTouch示例应用程序是一个很好的开始.但我希望我的应用程序逐一播放所有10首曲目.所有歌曲都添加到资源文件夹中,并命名为track1,track2 ... track10.

在avTouch应用程序代码中,我可以看到以下两个部分,我认为我需要进行更改以实现我正在寻找的内容.但我迷路了.

// Load the array with the sample file
NSURL *fileURL = [[NSURL alloc] 
                 initFileURLWithPath: 
                 [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"m4a"]];


- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (flag == NO)
    NSLog(@"Playback finished unsuccessfully");

[player setCurrentTime:0.];
[self updateViewForPlayerState];
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我
1.如何加载阵列与所有10个轨道添加到资源文件夹
2.当我点击播放时,播放器应该开始第一个轨道.当第一个轨道结束时,第二个轨道应该开始,依此类推剩下的轨道.

谢谢

iwa*_*bed 8

inScript,您找到了解决方案吗?你可能想要坚持一些简单的东西,就像一个if { // do something } else { // do something else }声明来背靠背地演奏它们.

要加载到数组中,请创建一个新的plist文件(右键单击目录树 - > Add - > New File"并在其中找到属性列表;将文件命名为soundslist.接下来打开该新文件,右键单击它所在的位置默认情况下说"字典",下到"值类型"并选择"数组"...如果你看到该行的最右边,你会看到一个小的3栏看按钮,点击它添加你的第一项.现在你一次添加一个项目,"track01","track02"等......每行一个.

此代码位于.h文件中:

NSArray* soundsList;
Run Code Online (Sandbox Code Playgroud)

此代码包含在.m文件中:

NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist" ofType:@"plist"];
soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];
Run Code Online (Sandbox Code Playgroud)

数组总是从索引#0开始...所以如果你有5个轨道,track01将是索引0,track02将是索引1,依此类推.如果您想快速轮询数组以查看其中的内容,可以添加以下代码:

int i = 0;

for (i; i <= ([soundsList count] - 1); i++) {

    NSLog(@"soundsList contains %@", [soundsList objectAtIndex:i]);

}
Run Code Online (Sandbox Code Playgroud)

所有这一切都是计算你的数组中有多少项目(即5或10或多少首歌曲),并objectAtIndex:以你发送到它的任何索引号返回对象.

对于背对背玩,你只需将if-then语句放在audioPlayerDidFinishPlaying方法中

如果要播放该文件,可以执行以下操作:

NSString* filename = [soundsList objectAtIndex:YOURINDEXNUMBER];
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"mp3"];  

AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];  
self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded

[newAudio release]; // release the audio safely

theAudio.delegate = self; 
[theAudio prepareToPlay];
[theAudio setNumberOfLoops:0];
[theAudio play];
Run Code Online (Sandbox Code Playgroud)

其中YOURINDEXNUMBER是你想要播放的任何曲目#(记住,0 = track01,1 = track02等)

如果您需要帮助在.h文件中设置变量,请告诉我,我可以引导您完成.另外,请记住theAudio在dealloc方法中释放,以便在程序退出时释放它.