首先加载AVFoundation.framework框架,然后加载一首自己喜欢的歌曲 .mp3
其他看代码。。。
#import <UIKit/UIKit.h>
#import "AVFoundation/AVFoundation.h"
@interface ViewController : UIViewController
{
AVAudioPlayer *player;
UISlider *proSlider;
UISlider *volSlider;
NSTimer *timer;
UIProgressView *progressView;
}
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//得到文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"xiguan" ofType:@"mp3"];
//本地路径 -> URL
NSURL *url = [NSURL fileURLWithPath:path];
//只支持本地文件,不支持在线播放
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//准备播放
[player prepareToPlay];
//播放速度
player.enableRate = YES;
//开启峰值平均检测
player.meteringEnabled = YES;
//声道
NSLog(@"%d",player.numberOfChannels);
//创建两个Button
for (int i=0; i<2; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(110, 10+40*i,100,30);
button.tag = i;
[self.view addSubview:button];
[button addTarget:self action:@selector(playControl:) forControlEvents:UIControlEventTouchUpInside];
}
//创建滑动条
proSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 100, 220, 0)];
//最小值
proSlider.minimumValue = 0.0;
//最大值
proSlider.maximumValue = 1.0;
//默认值
proSlider.value = 0.0;
//滑动事件
[proSlider addTarget:self action:@selector(progress) forControlEvents:UIControlEventTouchUpInside];
//添加到视图上
[self.view addSubview:proSlider];
[proSlider release];
volSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 130, 220, 0)];
volSlider.minimumValue = 0.0;
volSlider.maximumValue = 1.0;
volSlider.value = 0.5;
[volSlider addTarget:self action:@selector(volume) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:volSlider];
[volSlider release];
//进度条
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(50, 160, 220, 0)];
[self.view addSubview:progressView];
[progressView release];
}
- (void)volume
{
//声音 0.0-1.0
player.volume = volSlider.value;
//声道 -1.0左声道 0.0 1.0 右声道
player.pan = volSlider.value;
//播放速度 0.5半速 1.0 正常 2.0 倍速
player.rate = volSlider.value;
}
//调节进度
- (void)progress
{
player.currentTime = player.duration*proSlider.value;
}
- (void)refresh
{
//播放进度 = 当前时间/总时间
float pro = player.currentTime/player.duration;
//刷新进度条
[proSlider setValue:pro animated:YES];
//刷新峰值,平均值 0 ~ -160.0
[player updateMeters];
//得到峰值
float peak = [player peakPowerForChannel:0];
//平均值
float average = [player averagePowerForChannel:0];
[progressView setProgress:(average + 160)/160 animated:YES];
}
- (void)playControl:(UIButton*)button
{
//播放
if (button.tag == 0) {
[player play];
//开始刷新
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(refresh) userInfo:nil repeats:YES];
}
if (button.tag == 1) {
//暂停
[player pause];
//停止
//[player stop];
//结束刷新
if (timer) {
[timer invalidate];
timer = nil;
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end