1. 音频播放的第一种方式,AVAudioPlayer:
只能播放已缓存到本地的音频,功能相对简单,实现起来也很方便,不做重点讲解,代码如下:
#import <AVFoundation/AVFoundation.h>
/*
使用时,必须创建全局变量
*/
@interface LLAudioPlayer : AVAudioPlayer
- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;
- (id)initWithData:(NSData *)data error:(NSError **)outError;
- (void)startPlay;
- (void)pausePlay;
- (void)stopPlay;
@end
#import "LLAudioPlayer.h"
@interface LLAudioPlayer ()
@property (nonatomic, strong) AVAudioSession *audioSession;
@end
@implementation LLAudioPlayer
- (id)initWithContentsOfURL:(NSURL *)url error:(NSError * _Nullable __autoreleasing *)outError{
self = [super initWithContentsOfURL:url error:outError];
if (self) {
self.volume = 1.0; //音量 0.0-1.0之间
//self.numberOfLoops = 1; //循环次数 默认只播放一次
self.currentTime = 0.0; //播放位置 可以指定从任意位置开始播放
}
return self;
}
- (id)initWithData:(NSData *)data error:(NSError * _Nullable __autoreleasing *)outError{
self = [super initWithData:data error:outError];
if (self) {
self.volume = 1.0; //音量 0.0-1.0之间
//self.numberOfLoops = 1; //循环次数 默认只播放一次
self.currentTime = 0.0; //播放位置 可以指定从任意位置开始播放
}
return self;
}
- (void)startPlay{//播放
_audioSession = [AVAudioSession sharedInstance];
[_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[_audioSession setActive:YES error:nil];
[self prepareToPlay];//分配播放所需的资源,并将其加入内部播放队列
[self play];
}
- (void)pausePlay{//暂停
[self pause];
[_audioSession setActive:NO error:nil];
}
- (void)stopPlay{//停止
[self stop];
[_audioSession setActive:NO error:nil];
}
@end
2. 音频播放的第二种方式,AVPlayer:
话不多说,先上效果图:



代码比较多,就不一一解释了,感兴趣的童鞋可以下个demo看看,注释的很详细,就说几个注意事项:
1、如何实现后台播放;
2、处理中断事件,比如来电话时停止,电话挂断后恢复;
3、锁屏界面与交互处理。




基本功能已经实现,单曲循环、随机播放,顺序播放、查看播放列表等等,同时添加了音频文件出错时的错误处理,可放心使用。
网友评论