AVAudioplayer 是AVFoundation.framework 库中定义的一个类。
首先在工程中导入AVFoundation.framework 库。
AVAudioplayer 的使用
一,创建
- // 使用本地URL创建
- AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"发如雪" ofType:@"mp3"]] error:nil];
- // 创建NSData创建
- AVAudioPlayer *player2 = [[AVAudioPlayer alloc] initWithData:Data error:nil];
二,设置
- //1、音量
- self.player.volume =0.8;//0.0-1.0之间
- //2、循环次数
- self.player.numberOfLoops =3;//默认只播放一次
- //3、播放位置
- self.player.currentTime =15.0;//可以指定从任意位置开始播放
- //4、声道数
- NSUInteger channels = self.player.numberOfChannels;//只读属性
- //5、持续时间
- NSTimeInterval duration = self.player.duration;//获取持续时间
- //6、仪表计数
- self.player.meteringEnabled =YES;//开启仪表计数功能
- [player updateMeters];//更新仪表计数
四,播放音乐
AVAudioPlayerDelegate
- - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
- {
- //播放结束时执行的动作
- [audioButton setTitle:@"Play Audio File" forState:UIControlStateNormal];
- }
- - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error;
- {
- //解码错误执行的动作
- }
- - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player;
- {
- //处理中断的代码
- }
- - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
- {
- [audioPlayer play];
- }