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

2014-05-20  本文已影响4081人  陈旭冉

播放一个列表, 列表中有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];
}
上一篇下一篇

猜你喜欢

热点阅读