//以下代码用storyboard托控件实现
//导入头文件
#import<AVFoundation/AVFoundation.h>
@interface OnlineViewController()
//播放器
@property (nonatomic,strong)AVPlayer *avPlayer;
//监控进度
@property (nonatomic,strong)NSTimer *avTimer;
//进度条(托控件)
@property (weak, nonatomic) IBOutletUISlider *progress;
//音量条(托控件)
@property (weak, nonatomic) IBOutletUISlider *volume;
@end
@implementation OnlineViewController
– (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view.
//mp3播放网址
NSString *str =@”http://fdfs.xmcdn.com/group4/M02/28/FA/wKgDtFM052_jBsKhAAvPQEMti4w713.mp3″;
NSURL *url = [NSURLURLWithString:str];
//播放器初始化
self.avPlayer = [[AVPlayeralloc]initWithURL:url];
//设置播放器初始音量
self.avPlayer.volume =1;
//监控播放进度
self.avTimer = [NSTimerscheduledTimerWithTimeInterval:0.1target:selfselector:@selector(timer)userInfo:nilrepeats:YES];
//初始0音量
self.volume.value =5.0f;
//设置最大值最小值音量
self.volume.maximumValue =10.0f;
self.volume.minimumValue =0.0f;
}
//监控播放进度方法
– (void)timer
{
self.progress.value = CMTimeGetSeconds(self.avPlayer.currentItem.currentTime) / CMTimeGetSeconds(self.avPlayer.currentItem.duration);
}
//开始
– (IBAction)play:(id)sender {
[self.avPlayerplay];
}
//暂停
– (IBAction)pause:(id)sender {
[self.avPlayerpause];
}
//音量方法
– (IBAction)volum:(id)sender {
self.avPlayer.volume =self.volume.value;
}
AVPlayer的后台播放方法, 首先在AppDelegate的方法里写入
– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AVAudioSession *audioSession = [AVAudioSessionsharedInstance];
//默认情况下扬声器播放
[audioSession setCategory:AVAudioSessionCategoryPlaybackerror:nil];
[audioSessionsetActive:YESerror:nil];
}
之后在info文件里修改
这样就可以实现后台播放功能