美文网首页
使用AVAudioPlayer顺序播放多个音频文件

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

作者: 陈旭冉 | 来源:发表于2014-05-20 12:47 被阅读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];
    }

    相关文章

      网友评论

          本文标题:使用AVAudioPlayer顺序播放多个音频文件

          本文链接:https://www.haomeiwen.com/subject/jbcdtttx.html