iOS播放MP3音频

1.新建single view工程,导入AVFoundation库

2.ViewController.xib如图



3.ViewController.h文件

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController {
    //进度
    IBOutlet UISlider *_proSlider;
    //声道
    IBOutlet UISlider *_panSlider;
    //速度
    IBOutlet UISlider *_speedSlider;
    //音量
    IBOutlet UISlider *_volSlider;
    IBOutlet UIProgressView *_proV;
    IBOutlet UIProgressView *_proV2;
    
    AVAudioPlayer *_player;
    
    NSTimer *_timer;
}

- (IBAction)proSlider:(id)sender;
- (IBAction)panSlider:(id)sender;
- (IBAction)speedSlider:(id)sender;
- (IBAction)volSlider:(id)sender;

- (IBAction)play:(id)sender;
- (IBAction)pause:(id)sender;

@end

4.ViewController.m文件
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Beat It" ofType:@"mp3"];
//    NSURL *url = [NSURL URLWithString:path];//不能这样写,因为是本地路径
    NSURL *url = [NSURL fileURLWithPath:path];//本地路径应该这样写
    
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    //触发play事件的时候会将mp3文件加载到内存中,然后再播放,所以开始的时候可能按按钮的时候会卡,所以需要prepare
    [_player prepareToPlay];
    //设置支持变速
    _player.enableRate = YES;
    //峰值和平均值
    _player.meteringEnabled = YES;

}

- (void)play:(id)sender
{
    //按播放,开始定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(refresh) userInfo:nil repeats:YES];
    [_player play];
}

- (void)pause:(id)sender
{
    [_player pause];
    //定时器失效
    [_timer invalidate];
}

- (void)refresh
{
    //每隔0.1秒刷新一次进度,当前时间/总时间
    float pro = _player.currentTime/_player.duration;
    [_proSlider setValue:pro animated:YES];
    
    //averagePowerForChannel和peakPowerForChannel的属性分别为声音的最高振幅和平均振幅
    [_player updateMeters];//不刷新就永远是0
    float pead = ([_player peakPowerForChannel:0]+50)/50;//0左声道,1右声道
    float ave = ([_player averagePowerForChannel:0]+50)/50;//同上
    [_proV setProgress:pead animated:YES];
    [_proV2 setProgress:ave animated:YES];
}

//进度
- (IBAction)proSlider:(id)sender
{
    //当前时间=总时间*slider.value;
    float curTime = _player.duration*_proSlider.value;
    [_player setCurrentTime:curTime];
}
//声道
- (IBAction)panSlider:(id)sender
{
    _player.pan = _panSlider.value;
}
//速度
- (IBAction)speedSlider:(id)sender
{
    _player.rate = _speedSlider.value;
}
//音量
- (IBAction)volSlider:(id)sender
{
    _player.volume = _volSlider.value;
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值