可能没有最优雅的解决方案,但您会在这里找到一个常见的想法。这是一个完全有效的代码,您可以将其复制/粘贴到您的项目中,它应该可以工作。当然,您必须更改文件名。如果您有任何问题,请告诉我。
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface MainViewController () <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) NSMutableArray *soundsPathsList;
@property (nonatomic, assign) NSInteger curSoundIdx;
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
NSArray *soundList = [[NSArray alloc] initWithObjects:@"myAudioFile 1", @"myAudioFile 2", @"myAudioFile 3",
@"myAudioFile 4", @"myAudioFile 5", @"myAudioFile 6", @"myAudioFile 7",
@"myAudioFile 8", @"myAudioFile 9", @"myAudioFile 10", nil];
self.soundsPathsList = [NSMutableArray new];
for (NSString *fileName in soundList) {
NSString *pathToFile = [[NSBundle mainBundle] pathForResource:fileName ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:pathToFile];
[self.soundsPathsList addObject:url];
}
[self playNext];
}
return self;
}
- (void) playNext {
if (self.curSoundIdx >= [self.soundsPathsList count]) {
self.curSoundIdx = 0;
}
// destroy player object
[self.audioPlayer stop];
self.audioPlayer = nil;
// create new player object
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:
[self.soundsPathsList objectAtIndex:self.curSoundIdx] error:nil];
self.audioPlayer.delegate = self;
[self.audioPlayer play];
self.curSoundIdx++;
}
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[self playNext];
}
@end