使用AVAudioPlayer播放本地音乐

•使用AVAudioPlayer可以播放本地音乐,具备以下特点:
1.能够预先缓存,提高播放的流畅性(prepareToPlay)
2.播放起始时间(playAtTime)
3.播放控制(play/pause/stop)
4.循环播放次数(numberOfLoops)
5.播放音量(volume)
6.设置播放速度(enableRate/rate)
7.音量监控(meteringEnabled/peakPowerForChannel/averagePowerForChannel)
•除上述功能外,还可以通过AVAudioPlayer的代理方法监控音乐的播放进度
--------------------------------------------------------------------------------------------
 
代码步骤如下:
1.实例化AVAudioPlayer

NSError *error = nil;

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

if (error) {

    NSLog(@"加载音乐播放器失败 - %@", error.localizedDescription);

    return nil;

}

return player;

2.AVAudioPlayer播放时的音量监控

•应用场景:诵读类App的播放时长截取

// 1. 加载朗诵音频

_player = [SoundTool audioPlayerWithName:@"上01一东.mp3"];

_player.numberOfLoops = 0;

[_player prepareToPlay];

[_player setDelegate:self];

// 2. 允许音量测量

[_player setMeteringEnabled:YES];

// 3. 实例化音频信息数组

_soundInfo = [NSMutableArray array];

// 4. 启动时钟

_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

// 5. 开始播放

[_player play];

3.时钟处理方法

// 1. 更新播放器音量

[_player updateMeters];

// 2. 判断是否需要记录

if ([_player averagePowerForChannel:0] > -50.0) {

    if (_shouldRecord) {

        NSLog(@"%f", [_player currentTime]);

        if (![_soundInfo containsObject:@([_player currentTime])]) {

            [_soundInfo addObject:@([_player currentTime])];

        }

    }

    _shouldRecord = NO;

} else {

    _shouldRecord = YES;

}

posted on 2013-12-10 22:04  林源  阅读(1494)  评论(0编辑  收藏  举报

导航