三、相关说明
新建一个项目,在storyboard中放三个按钮,分别用来控制音乐的播放、暂停和停止。
程序代码如下:
复制代码#import "YYViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface YYViewController ()
@property(nonatomic,strong)AVAudioPlayer *player;
- (IBAction)play;
- (IBAction)pause;
- (IBAction)stop;
@end
@implementation YYViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//1.音频文件的url路径
NSURL *url=[[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:Nil];
//2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
//3.缓冲
[self.player prepareToPlay];
}
- (IBAction)play {
//开始播放/继续播放
[self.player play];
}
- (IBAction)pause {
//暂停
[self.player pause];
}
- (IBAction)stop {
//停止
//注意:如果点击了stop,那么一定要让播放器重新创建,否则会出现一些莫名其面的问题
[self.player stop];
}
@end
注意:如果点了“停止”,那么一定要播放器重新创建,不然的话会出现莫名其妙的问题。
点击了stop之后,播放器实际上就不能再继续使用了,如果还继续使用,那么后续的一些东西会无法控制。











