// ViewController.h
// 音频播放
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@end
// ViewController.m
// 音频播放
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioPlay; //音频播放器
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ViewController
-(NSTimer *)timer
{
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgressView) userInfo:nil repeats:YES];
}
return _timer;
}
#pragma mark 更新播放进度条
-(void)updateProgressView
{
float pregressNum = _audioPlay.currentTime/_audioPlay.duration;
[_progressView setProgress:pregressNum animated:YES];
}
-(void)audioPlay1
{
if (!_audioPlay) {
//得到音频路径
NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"music3.mp3" ofType:nil];
//1.1.通过URL初始化音频播放器(只能是本地的URL)
NSURL *audioUrl = [NSURL fileURLWithPath:audioPath];
_audioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:audioUrl error:nil];
//1.2. 通过NSData初始化音频播放器
// NSData *audioData = [NSData dataWithContentsOfFile:audioPath];
// _audioPaly = [[AVAudioPlayer alloc] initWithData:audioData error:nil];
//播放重复的次数 -1为循环播放
_audioPlay.numberOfLoops = 0;
//设置声音大小 0.0-1.0
_audioPlay.volume = 0.5;
//获取音频的持续时间 (只读)
NSLog(@"%f",_audioPlay.duration) ;
//从开始播放到结束的总时间,包括中间暂停的时间
// _audioPaly.deviceCurrentTime;
//获取音频声道数 (只读)
NSLog(@"%i",_audioPlay.numberOfChannels);
//播放速率 1为正常
_audioPlay.enableRate = YES;
_audioPlay.rate = 1;
//立体声平衡: (-1.0~1.0) -1.0完全是左声道,1.0完全是右声道
_audioPlay.pan = 0.0;
//2.加载音频文件到缓存中
// [_audioPlay prepareToPlay];
_audioPlay.delegate = self;
// //锁屏之后仍然继续播放
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
// [[AVAudioSession sharedInstance] setActive:YES error:nil];
}
// return _audioPlay;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self audioPlay1];
}
#pragma mark 播放
- (IBAction)palyAudio:(id)sender {
if (![self audioPlay].isPlaying) {
[_audioPlay play];
[self timer].fireDate = [NSDate distantPast]; //恢复定时器
}
}
#pragma mark 暂停
- (IBAction)pauseAudio:(id)sender {
if (_audioPlay.playing) {
[_audioPlay pause];
[self timer].fireDate = [NSDate distantFuture]; //暂停定时器
}
}
#pragma mark 停止
- (IBAction)stopAudio:(id)sender {
if (_audioPlay.playing) {
[_audioPlay stop];
_audioPlay.currentTime = 0;
[_progressView setProgress:0 animated:YES
];
[self timer].fireDate = [NSDate distantFuture]; //暂停定时器
}
}
#pragma mark 协议中的方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(@"播放完成");
}
#pragma mark 被系统任务打扰,可以先暂停播放
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
if (_audioPlay) {
[_audioPlay pause];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
音频播放小操作
最新推荐文章于 2024-09-12 13:44:24 发布