一個基於StreamingKit第三方框架簡單的音頻播放器
GitHub開源框架:https://github.com/tumtumtum/StreamingKit
主要功能
- 上一首、下一首、暫停、播放、切換播放模式、操作進度條等。
如圖所示

- 封裝STKAudioPlayer播放器
/** 單例 */
+ (instancetype)shareInstance;
/** 播放指定音頻
@param URL 音頻地址
*/
- (void)ym_playWithURL:(NSURL *)URL;
/** 暫停 */
- (void)ym_pause;
/** 繼續 */
- (void)ym_resume;
/** 結束播放 */
- (void)ym_stop;
/** 從指定時間開始播放
@param time 開始播放的時間
*/
- (void)ym_seekToTime:(double)time;
- STKAudioPlayer的代理方法
- 音頻開始播放
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId {
YMLog(@"開始播放 : %@",queueItemId);
}
- 當一個項目已完成緩沖時引發(可能是也可能不是當前正在播放的項目)
- 如果在播放器上調用seek,則同一項可能引發多次此事件
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId {
YMLog(@"緩沖完成 : %@",queueItemId);
}
- 當播放器狀態改變時觸發
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState {
YMLog(@"播放器狀態改變:%@",@(state));
}
- 當音頻播放結束時觸發
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration {
YMLog(@"播放完成:%@",queueItemId);
}
- 當發生意外且可能無法恢復的錯誤時引發(通常最好重新創建STKAudioPlauyer)
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode {
YMLog(@"播放錯誤:%@",@(errorCode));
}
- 可選實現從STKAudioPlayer獲取日志信息(內部用於調試)
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line {
YMLog(@"播放日志:%@",line);
}
- 清除隊列中的項時引發(通常是因為調用play、setDataSource或stop)
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems {
}
- 音頻開始播放是定義了一個開始播放的block,這里主要用於音頻開始播放的時候旋轉動畫
@property (nonatomic, copy, nullable) void(^startPlayBlock)(NSURL *URL);
player.startPlayBlock = ^(NSURL * _Nonnull URL) {
YMLog(@"開始播放:%@",URL);
[ws.iconView resumeRotate]; //開始轉動封面
[ws.phonePlayerColView startPlayingMusic];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTitle" object:nil userInfo:@{@"name":ws.phonePlayerColView.currentModel.name}];
//更新圖片
ws.iconView.imageUrl = ws.phonePlayerColView.currentModel.imageUrl;
};
- 音頻結束后,停止動畫
@property (nonatomic, copy, nullable) void(^finishPlayBlock)(NSURL *URL);
player.finishPlayBlock = ^(NSURL * _Nonnull URL) {
YMLog(@"播放完成:%@",URL);
[ws.iconView stopRotating];//停止動畫
};
- 需要時時更新音頻的時長,進度,播放狀態等一些信息,取出然后賦值到頁面上,這里使用block回傳數據
player.refreshBlock = ^(double duration, double progress, STKAudioPlayerState state, STKAudioPlayerErrorCode errorCode) {
YMLog(@"時長:%f",duration);
YMLog(@"進度:%f",progress);
YMLog(@"播放狀態:%ld",(long)state);
YMLog(@"播放error:%ld",(long)errorCode);
}
Demo連接:https://github.com/AndrewLJJ/MusicPlayer
掘金地址:https://juejin.im/post/5dc0da0ce51d4529ef3ef823
