ios 音乐播放

时间:2023-03-09 06:54:49
ios 音乐播放

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property(nonatomic,strong)AVAudioPlayer*player;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//添加两个按钮

UIButton *playBtn=[UIButton buttonWithType:UIButtonTypeCustom];

playBtn.backgroundColor=[UIColor grayColor];

playBtn.frame=CGRectMake(10, 10, 100, 50);

[self.view addSubview:playBtn];

[playBtn addTarget:self action:@selector(playMusic) forControlEvents:UIControlEventTouchUpInside];

UIButton *pauseBtn=[UIButton buttonWithType:UIButtonTypeCustom];

pauseBtn.backgroundColor=[UIColor grayColor];

pauseBtn.frame=CGRectMake(10, 70, 100, 50);

[self.view addSubview:pauseBtn];

[pauseBtn addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];

}

//懒加载初始化音乐播放类

-(AVAudioPlayer *)player

{

if (!_player) {

NSString *path=[[NSBundle mainBundle]pathForResource:@"我爱你你却爱着她.mp3" ofType:nil];

NSURL *url=[NSURL fileURLWithPath:path];

//创建播放器对象

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

//记录

_player=player;

//缓存准备

[_player prepareToPlay];

}

return _player;

}

//开始播放

-(void)playMusic

{

[self.player play];

}

//暂停

-(void)pause

{

[self.player pause];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

@end