iphone - 如何在AVAudioplayer中播放多个文件

标签 iphone xcode audio avaudioplayer

我在plist中有一些歌曲,想使用AVAudioplayer播放一首。
但是当第一首歌曲结束时,它停止了。如何开始播放下一首歌曲?
我尝试了一个循环,该循环计数到plist中的下一个数字,但是它不起作用。玩家在第一轮后停止。这应该很简单,但是如何?
这是我的代码的一部分。是否可以像我一样使用循环?

    NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist"  
ofType:@"plist"];
soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];


 for (int n = 1; n<=5;n++) {
NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

 sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

sound.delegate = self;
 }

最佳答案

尝试这样可以帮助您,

-(void)viewDidLoad{

 NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist"  
ofType:@"plist"];
soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];
[self AddSongToAvplayer];
}

-(void)AddSongToAvplayer{

NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

 sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

sound.delegate = self;
n++;


 if(n<=[sound count])
    [NSTimer scheduledTimerWithTimeInterval:sound.duration target:self selector:@selector(AddSongToAvplayer) userInfo:nil repeats:NO];
}

在上面的代码中sound.duration给出了该特定歌曲的timeInterval,并基于该歌曲的完成时间后,您可以使用计时器调用该方法。如果最后一首歌曲出现,则停止该NSTimer

编辑:
-(IBAction)AddSongToAvplayer{
        if(n<=[sound count]){

    NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

     sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

    sound.delegate = self;
    n++;

    }

    }

关于iphone - 如何在AVAudioplayer中播放多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15677897/

相关文章:

arrays - 为什么我不能在 Swift 中创建返回 "Array"而不是 NSArray 的函数?

ios - 屏幕截图出现在 iTunesConnect 而不是 Appstore

iphone - 如何对在iPhone上录制的IMA4 ADPCM音频文件进行转码?

iphone - 如何在 if 语句中检查 UILabel 的值是否大于 0?

javascript - 我简单的JavaScript游戏中使用音频的声音无法播放

ios - 在 iOS 中通知 A 类关于 B 类的最佳方式

javascript - 使用 Typedjs 在每个字符处播放声音

iphone - URL 主机名返回 null

iphone - 从 Google App Engine 的数据存储中获取实体以用于 iOS 应用

ios - 无法将类型 'UITableViewCell' 的值转换为 'AppName.CustomCellName'