iOS开发实现音频播放功能
音频播放
1、介绍
-功能介绍
用于播放比较长的音频、说明、音乐,使用到的是AVFoundation
-框架介绍
*AVAudioPlayer
*初始化:
注意:
(3)必须声明全局变量的音乐播放对象、或者是属性的音乐播放对象 才可以播放
(4)在退出播放页面的时候一定要把播放对象置空 同时把delegate置空
导入框架:#import<AVFoundation/AVFoundation.h>
声明全局变量
@interfaceViewController()<AVAudioPlayerDelegate>
{
AVAudioPlayer*audioPlayer;
}
@end
音频的基本属性
预播放[audioPlayerprepareToPlay];
获取 当前音乐的声道audioPlayer.numberOfChannels
audioPlayer.currentTime//当前播放的时间
audioPlayer.playing//判断是否正在播放
audioPlayer.numberOfLoops;//设置循环播放的此次
audioPlayer.duration 获得播放音频的时间
audioPlayer.pan 设置左右声道效果
audioPlayer.volume设置音量0.0-1.0 是一个百分比
//设置速率必须设置enableRate为YES; audioPlayer.enableRate=YES; audioPlayer.rate=3.0;
音量audioPlayer.volume=0.1;
设置播放次数负数是无限循环的0是一次1是两次依次类推audioPlayer.numberOfLoops=0;
获得当前峰值audioPlayerpeakPowerForChannel:2
平均峰值
audioPlayeraveragePowerForChannel:2
音频播放的几个代理方法
//播放完成的时候调用
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)playersuccessfully:(BOOL)flag{
NSLog(@"播放完成");
}
//解码出现错误的时候调用
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)playererror:(NSError*__nullable)error{
}
//开始被打扰中断的时候调用
-(void)audioPlayerBeginInterruption:(AVAudioPlayer*)player{
}
//中断结束后调用
-(void)audioPlayerEndInterruption:(AVAudioPlayer*)playerwithOptions:(NSUInteger)flags{
}
实例解析音频播放
初始化一个按钮
在ViewDidLoad中
UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom]; button.frame=CGRectMake(100,100,100,100); button.backgroundColor=[UIColorbrownColor]; [buttonsetTitle:@"Play"forState:UIControlStateNormal]; [buttonsetTitle:@"Pause"forState:UIControlStateSelected]; [buttonaddTarget:selfaction:@selector(play:)forControlEvents:UIControlEventTouchUpInside]; [self.viewaddSubview:button]; [selfplayMusicWithName:@"TFBOYS-青春修炼手册.mp3"];
按钮的触发方法:
-(void)play:(UIButton*)sender{
sender.selected=!sender.selected;
sender.selected!=YES?[audioPlayerpause]:[audioPlayerplay];
}
-(void)playMusicWithName:(NSString*)name{
NSError*error;
//创建一个音乐播放对象
audioPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:[[NSBundlemainBundle]URLForResource:namewithExtension:nil]error:&error];
if(error){
NSLog(@"%@",error);
}
预播放
[audioPlayerprepareToPlay];
播放在这里不写在这但它是必须的步骤
[audioPlayerplay];
获取当前音乐的声道
NSLog(@"%ld",audioPlayer.numberOfChannels);
durtion:获得播放音频的时间
设置声道-1.0左0.0中间1.0右
audioPlayer.pan=0.0;
音量
audioPlayer.volume=0.1;
设置速率必须设置enableRate为YES
audioPlayer.enableRate=YES;
设置速率0.5是一半的速度1.0普通2.0双倍速率
audioPlayer.rate=1.0;
currentTime获得时间
获得峰值必须设置meteringEnabled为YES
audioPlayer.meteringEnabled=YES;
更新峰值
[audioPlayerupdateMeters];
获得当前峰值
NSLog(@"当前峰值:%f",[audioPlayerpeakPowerForChannel:2]);
NSLog(@"平均峰值%f",[audioPlayeraveragePowerForChannel:2]);
设置播放次数负数是无限循环的0是一次1是两次依次类推
audioPlayer.numberOfLoops=0;
挂上代理
audioPlayer.delegate=self;
}