1、首先,音频播放的实现,我这里使用的是AVPlayer
。
AVAudioPlayer
只能播放本地资源。当然还有别的播放方法这里就不列举了。
以下代码实现的是如下图所示的效果,点击图标可以暂停或者继续播放:
需要的属性:
//
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) UIImageView *playerView;
@property (nonatomic, strong) UILabel *timeL;
@property (nonatomic, strong) UIImageView *animationV;//加载动画
初始化属性
//
- (AVPlayer *)player
{
if (_player == nil) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kVedioUrl,_playItemInfo[@"ypwj"]]];
AVAsset *avset = [AVAsset assetWithURL:url] ;
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:avset];
_item = item;
// 创建AVPlayer
_player = [AVPlayer playerWithPlayerItem:_item];
// 添加AVPlayerLayer
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
layer.frame = CGRectMake(self.view.bounds.size.width - 55, self.view.bounds.size.height - 100, 50, 50);
[self.view.layer addSublayer:layer];
//监听是否可播放
[_item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//监听缓存状态,可以添加加载动画
[_item addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
//监听是否播放完成
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToTheEnd) name:AVPlayerItemDidPlayToEndTimeNotificat