播放一個(gè)列表, 列表中有A.mp3, B.mp3, C.mp3...
第一步: 頭文件
@interface PlayerViewController : UIViewController <AVAudioPlayerDelegate>
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) NSArray *arrayOfTracks; // 這個(gè)數(shù)組中保存音頻的名稱
@end
第二步: m文件中麦到,設(shè)置變量凶掰,記錄待播放音頻的數(shù)量
@interface PlayerViewController ()
{
NSUInteger currentTrackNumber;
}
第三步: 實(shí)現(xiàn)這個(gè)代理方法
- (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];
}