ewDidLoad {
[super viewDidLoad];
//iOS9处理中断
AVAudioSession * session = [AVAudioSession sharedInstance];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Interruption:) name:AVAudioSessionInterruptionNotification object:session];
}
//iOS9中断处理方法
- (void)Interruption:(NSNotification *)noti{
if (noti.userInfo.allKeys.count == 2) {
NSLog(@"结束中断");
}else{
NSLog(@"开始中断");
}
}
一页的代码就把代码贴上了
//
// ViewController.m
// 音乐
//
// Created by ma c on 16/5/11.
// Copyright © 2016年 xubaoaichiyu. All rights reserved.
//
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
//播放本地音乐
@property (nonatomic, strong) AVAudioPlayer * player;
//播放时间的滑块
@property (weak, nonatomic) IBOutlet UISlider *timeSlider;
//定时器
@property (nonatomic, strong) CADisplayLink * link;
@end
@implementation ViewController
#pragma mark - <getters and setters>
- (CADisplayLink *)link{
if (!_link) {
_link = [CADisplayLink displayLinkWithTarget:self selector:@selector(change)];
}
return _link;
}
- (AVAudioPlayer *)player{
if (!_player) {
NSURL * url = [[NSBundle mainBundle]URLForResource:@"CX" withExtension:@"mp3"];
NSError * error;
//实例化播放
_player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
//设置代理
_player.delegate = self;
if (error) {
NSLog(@"初始化失败");
}else{
//准备开始播放 缓冲数据
[_player prepareToPlay];
//是否允许快播
_player.enableRate = YES;
//设置播放次数 -1为无限
//0:播放一次 1:播放两次 ......
_player.numberOfLoops = 0;
//slider最大值
self.timeSlider.maximumValue = _player.duration;
}
}
return _player;
}
#pragma mark - <life cycle>
- (void)viewDidLoad {
[super viewDidLoad];
//iOS9处理中断
AVAudioSession * session = [AVAudioSession sharedInstance];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(Interruption:) name:AVAudioSessionInterruptionNotification object:session];
}
#pragma mark - <AVAudioPlayerDelegate>
//播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
}
//error
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
}
//iOS8 开始中断
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
}
//iOS8 结束中断
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player{
}
#pragma mark - <event handle>
//改变slider进度的方法
- (void)change{
//获取当前时间 重置播放进度
self.timeSlider.value = self.player.currentTime;
}
//iOS9中断处理方法
- (void)Interruption:(NSNotification *)noti{
if (noti.userInfo.allKeys.count == 2) {
NSLog(@"结束中断");
}else{
NSLog(@"开始中断");
}
}
//播放
- (IBAction)play:(id)sender {
if (![self.player isPlaying]) {
//添加定时器到runloop中
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[self.player play];
}
}
//暂停
- (IBAction)pause:(id)sender {
if ([self.player isPlaying]) {
[self.player pause];
//暂停link
[self.link invalidate];
self.link = nil;
}
}
//停止
- (IBAction)stop:(id)sender {
[self.player stop];
//清空内存
self.player = nil;
//停止link
[self.link invalidate];
self.link = nil;
}
//按下slieder 开始拖拽
- (IBA