1

我在 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;
 }
4

1 回答 1

1

像这样尝试它会帮助你,

-(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中给出了那首特定歌曲的时间间隔,并基于该歌曲完成后,您可以使用计时器调用该方法。如果最后一首歌曲来了,则停止该方法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++;

    }

    }
于 2013-03-28T09:15:37.770 回答