播放一个列表, 列表中有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];
}
网友评论