#import "ViewController.h"
#import <AVFoundation/AVFoundation.h> //音频视频框架
@interface ViewController ()
//音频播放器
@property(nonatomic,strong)AVAudioPlayer *player;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 播放音乐按钮
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn1.frame=CGRectMake(50,50,100,100);
[btn1setTitle:@"播放音乐" forState:UIControlStateNormal];
[btn1addTarget:self action:@selector(playBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
// 暂停音乐按钮
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn2.frame=CGRectMake(50,150,100,100);
[btn2setTitle:@"暂停音乐" forState:UIControlStateNormal];
[btn2addTarget:self action:@selector(pauseBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
// 停止音乐按钮
UIButton *btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn3.frame=CGRectMake(50,250,100,100);
[btn3setTitle:@"停止音乐" forState:UIControlStateNormal];
[btn3addTarget:self action:@selector(stopBtn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn3];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"徐佳莹 - 不醉不会.m4a" withExtension:nil];
//创建播放器
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
}
//播放音乐
-(void)playBtn{
//播放
[self.player prepareToPlay];
//播放频率
// self.player.enableRate = YES;
// self.player.rate = 2;
//暂停/播放 切换
if(self.player.isPlaying) {
//暂停
[self.playerpause];
}else{
[self.playerplay];
}
}
//暂停音乐
-(void)pauseBtn{
//暂停/播放 切换
if(self.player.isPlaying) {
//暂停
[self.playerpause];
}else{
[self.playerplay];
}
}
//停止音乐
-(void)stopBtn{
//停止音乐
[self.playerstop];
//归零操作
self.player.currentTime = 0;
}