如何在AVAudioPlayer中连续播放多个audio文件?

我的应用程序中有5首歌曲,我想用AVAudioPlayer一个接一个播放。

有没有这样的例子? 我怎样才能做到这一点?

任何示例代码将不胜感激!

谢谢!

对于你想制作一个AVPlayer每首歌曲。

NSURL *url = [NSURL URLWithString:pathToYourFile];
AVPlayer *audioPlayer = [[AVPlayer alloc] initWithURL:url];
[audioPlayer play];

当玩家结束时你可以得到一个通知。 设置播放器时检查AVPlayerItemDidPlayToEndTimeNotification

  audioPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[audioPlayer currentItem]]; 

这将防止玩家在最后暂停。

在通知中:

 - (void)playerItemDidReachEnd:(NSNotification *)notification { // start your next song here } 

只要您收到当前播放歌曲完成的通知,您就可以开始播放下一首歌曲。 保持一些在select器调用中持久的计数器。 这种方式使用counter % [songs count]将给你一个无限循环的播放列表:)

当释放播放器时,不要忘记取消注册通知。

AVQueuePlayer适用于这种情况。

AVQueuePlayer是AVPlayer的一个子类,用于依次播放多个项目。

你可以使用AVQueuePlayer来代替AVAudioPlayer,它可以像Ken所build议的那样更好地适应这个用例。 这里有一些你可以使用的代码:

 @interface AVSound : NSObject @property (nonatomic, retain) AVQueuePlayer* queuePlayer; - (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType; - (void)playQueue; @end @implementation AVSound - (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType { // Path to the audio file NSString *path = [[NSBundle mainBundle] pathForResource:pathForResource ofType:ofType]; // If we can access the file... if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]]; if (_queuePlayer == nil) { _queuePlayer = [[AVQueuePlayer alloc] initWithPlayerItem:item]; }else{ [_queuePlayer insertItem:item afterItem:nil]; } } } - (void)playQueue { [_queuePlayer play]; } @end 

然后使用它:在你的界面文件中:

 @property (strong, nonatomic) AVSound *pageSound; 

在你的实现文件中:

 - (void)addAudio:(Book*)book pageNum:(int)pageNum { NSString *soundFileEven = [NSString stringWithFormat:@"%02d", pageNum-1]; NSString *soundPathEven = [NSString stringWithFormat:@"%@_%@", book.productId, soundFileEven]; NSString *soundFileOdd = [NSString stringWithFormat:@"%02d", pageNum]; NSString *soundPathOdd = [NSString stringWithFormat:@"%@_%@", book.productId, soundFileOdd]; if (_pageSound == nil) { _pageSound = [[AVSound alloc]init]; _pageSound.player.volume = 0.5; } [_pageSound clearQueue]; [_pageSound addToPlaylist:soundPathEven ofType:@"mp3"]; [_pageSound addToPlaylist:soundPathOdd ofType:@"mp3"]; [_pageSound playQueue]; } 

HTH

不幸的是,AVAudioPlayer只能播放一个文件。 要播放两个文件,必须先杀掉AVAudioPlayer的第一个实例,然后重新创build它(可以使用- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError )来启动它。 这种方法的问题是在第一个文件播放完毕和第二个文件开始播放之间有一点点延迟。 如果你想摆脱这种延迟,你必须挖掘核心audio,并提出一个更复杂的解决scheme。