我在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/