您的位置:首页 > 运维架构

使用AVAudioPlayer顺序播放多个音频文件

2014-11-03 15:42 435 查看
播放一个列表, 列表中有A.mp3, B.mp3, C.mp3...

第一步: 头文件
@interface PlayerViewController : UIViewController <AVAudioPlayerDelegate>
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) NSArray *arrayOfTracks; // 这个数组中保存音频的名称
@end


第二步: m文件中,设置变量,记录待播放音频的数量
@interface PlayerViewController ()
{
NSUInteger currentTrackNumber;
}


第三步: 实现这个代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (flag) {
if (currentTrackNumber < [_arrayOfTracks count] - 1) {
currentTrackNumber ++;
if (_audioPlayer) {
[_audioPlayer stop];
_audioPlayer = nil;
}
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[_arrayOfTracks objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL];
_audioPlayer.delegate = self;
[_audioPlayer play];
}
}
}


第四步: 播放
- (void)startPlaying
{
if (_audioPlayer) {
[_audioPlayer stop];
_audioPlayer = nil;
} else {
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[NSString alloc] initWithString:[_arrayOfTracks objectAtIndex:currentTrackNumber]] ofType:@"mp3"]] error:NULL];
_audioPlayer.delegate = self;
[_audioPlayer play];
}
}


第五步: 停止播放
- (IBAction)stop:(id)sender
{
[_audioPlayer stop];
}


第六步: 重新播放
- (IBAction)restart:(id)sender
{
[[AFSoundManager sharedManager] restart];
_audioPlayer = nil;
currentTrackNumber = 0;
[self startPlaying];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: