How do I play multiple files in AVAudioplayer

醉酒当歌 提交于 2019-12-12 01:35:34

问题


I have some songs in a plist and want to play them one after the other using AVAudioplayer. But when the first song ends it stops. How do I start the player with next song? I have tried a loop which counts to next number in the plist but it does not work. The player stops after first round. This should be simple but how? This is parts of my code. Is it is possible to use a loop as I do?

    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;
 }

回答1:


try like this it'l helps you,

-(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];
}

in the above code sound.duration gives the timeInterval of that particular song and based on that after completion of that song you can call that method by using the timer .if the last song coming then stop that NSTimer.

EDIT:

-(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++;

    }

    }


来源:https://stackoverflow.com/questions/15677897/how-do-i-play-multiple-files-in-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!