iOS 播放音乐
制作播放视频
首先先导入 以下框架
ViewController.h
引入<AVFoundation/AVFoundation.h>头文件
遵守AVAudioPlayerDelegate协议
创建控制器属性
//音频控件
@property (nonatomic,strong)AVAudioPlayer *thePlayer;
//进度条
@property (nonatomic,strong)UIProgressView *theProgress;
//按钮
@property (nonatomic,strong)UIButton *theBtn;
//定时器
@property (nonatomic,strong)NSTimer *theTimer;
//进度条
-(UIProgressView *)theProgress{
if (!_theProgress) {
//初始化进度条
_theProgress = [[UIProgressView alloc]initWithFrame:CGRectMake(100, 200, 200, 20)];
}
return _theProgress;
}
-(UIButton *)theBtn{
if (!_theBtn) {
//创建按钮状态
_theBtn = [UIButton buttonWithType: UIButtonTypeRoundedRect];
//设置按钮位置
_theBtn.frame = CGRectMake(100, 260, 200, 44);
//添加按钮名称
[_theBtn setTitle:@"▶️" forState:UIControlStateNormal];
//给按钮添加点击事件
[_theBtn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
return _theBtn;
}
-(NSTimer *)theTimer{
if (!_theTimer) {
//设置定时器
_theTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
return _theTimer;
}
-(void)timer{
//设置时间
CGFloat Number = self.thePlayer.currentTime / self.thePlayer.duration;
//赋值给进度条
[self.theProgress setProgress:Number animated:YES];
}
-(AVAudioPlayer *)thePlayer{
if (!_thePlayer) {
//取出文件路径
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"十年.mp3" ofType:nil];
//转换为NSURL状态
NSURL *url = [NSURL fileURLWithPath:filePath];
//初始化音频对象
_thePlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
//设置是否单曲循环播放 0 不循环 N次 循环N次 -1无限循环
_thePlayer.numberOfLoops = 0;
//设置代理
_thePlayer.delegate = self;
//将音频添加到缓存中。 准备播放
[_thePlayer prepareToPlay];
}
return _thePlayer;
}
-(void)click:(UIButton *)btn{
NSString *newStr = btn.titleLabel.text;
if ([newStr isEqualToString:@"▶️"]) {
[self.theBtn setTitle:@"⏸" forState:UIControlStateNormal];
if (![self.thePlayer isPlaying]) {
[self.thePlayer play];
self.theTimer.fireDate = [NSDate distantPast];
}
}if ([newStr isEqualToString:@"⏸"]) {
[self.theBtn setTitle:@"▶️" forState:UIControlStateNormal];
[self.thePlayer pause];
self.theTimer.fireDate = [NSDate distantFuture];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[self.theBtn setTitle:@"▶️" forState:UIControlStateNormal];
}
ViewDidLoad 方法里添加控件到视图
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.theProgress];
[self.view addSubview:self.theBtn];
}