iOS使用AVPlayer自定義音頻播放器

下一篇:iOS使用AVPlayer自定義視頻播放器

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:

話不多說,先上效果圖:

LLAudioPlayer-播放界面.png
LLAudioPlayer-歌曲列表.png
LLAudioPlayer-鎖屏界面.jpg

github下載地址:https://github.com/wangzhaomeng/LLAudioPlayer

代碼比較多,就不一一解釋了,感興趣的童鞋可以下個demo看看,注釋的很詳細,就說幾個注意事項:
1、如何實現后臺播放;
2、處理中斷事件,比如來電話時停止,電話掛斷后恢復;
3、鎖屏界面與交互處理。


后臺設置.png
實現監聽.png
注冊后臺與處理中斷.png
設置鎖屏界面.png

基本功能已經實現,單曲循環、隨機播放,順序播放、查看播放列表等等,同時添加了音頻文件出錯時的錯誤處理,可放心使用。

覺得好,就給個star,謝謝!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容