这两者简单使用,话不多说,我们直接来看代码吧。
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h> // xcode6.0以后 直接导入该框架即可@interface ViewController : UIViewController
{
__weak IBOutlet UILabel *_timeLabel;//时间显示Label
}
@property (weak, nonatomic) IBOutlet UISlider *Slider; //播放进度滑动条
@property (weak, nonatomic) IBOutlet UISlider *voliSlider; //播放进度滑动条
@end
#import "ViewController.h"
@interface ViewController ()
{
AVAudioPlayer *_player; //只能播放本地音乐
// AVPlayer *_player; //能播放本地音乐 和 流媒体音乐
//记录播放时间
NSTimer *timer;
// BOOL isPlaying;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//———————————————————————————AVAudioPlayer————————————————————————————————
// NSURL *url1=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music1.mp3" ofType:nil]];
NSURL *url2=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Taylor Swift - Blank Space [mqms].mp3" ofType:nil]];
//只能播放本地音乐
_player=[[AVAudioPlayer alloc] initWithContentsOfURL:url2 error:nil];
//播放总时间
_Slider.maximumValue=_player.duration;
//———————————————————————————AVPlayer————————————————————————————————————
// NSString *urlPath=@"http://qqmusic.4ftt.com/m/101369814.mp3?20150318133115";
// NSURL *url=[NSURL URLWithString:urlPath];
// //能播放本地音乐 和 流媒体音乐
// _player=[[AVPlayer alloc] initWithURL:url];
//———————————————————————————————————————————————————————————————————————
/*
AVAudioPlayer 与 AVPlayer 共同属性
*/
//播放次数 默认为0(播放一次)1 即是 播放2次 -1或者无穷大的数 为无限循环
_player.numberOfLoops=1;
//播放音量默认1
_player.volume=.5;
//播放音量
_voliSlider.value=.5;
// [_player play]; //播放
// [_player stop]; //停止
// [_player pause]; //暂停
}
//播放事件
- (IBAction)PlayerAction:(UIButton *)sender {
if (_player.isPlaying) {
[_player pause];
[timer invalidate];
}else{
[_player play];
//开启定时器
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
}
//定时器事件
- (void)timerAction:(NSTimer *)time
{
//播放滑块的值设定为音乐播放当前时间
_Slider.value=_player.currentTime;
NSInteger timerun=(NSInteger)_player.currentTime;
//时间 67 格式转化为 文本 01:07 显示样式
if (timerun%60<10)
{
if (timerun/60>0) {
NSString *test=[NSString stringWithFormat:@"0%ld:0%ld",timerun/60,timerun-60*(timerun/60)];
_timeLabel.text=test;
}else
{
NSString *test=[NSString stringWithFormat:@"0%ld:0%ld",timerun/60,timerun];
_timeLabel.text=test;
}
}else if(timerun%60>=10)
{
if (timerun/60>0) {
NSString *test=[NSString stringWithFormat:@"0%ld:%ld",timerun/60,timerun-60*(timerun/60)];
_timeLabel.text=test;
}else
{
NSString *test=[NSString stringWithFormat:@"0%ld:%ld",timerun/60,timerun];
_timeLabel.text=test;
}
}
}
//播放进度滑动事件
- (IBAction)Slider:(UISlider *)sender {
//播放当前时间等于滑动条滑动的值
_player.currentTime=sender.value;
}
//播放音量滑动事件
- (IBAction)voliAction:(UISlider *)sender {
_player.volume=sender.value;
}
@end
上述控件都在 Main.storyboard 画好了 两个UISlider也连接好了事件,相信这些简单操作难不倒读者吧,好了大家去试一试吧。