AVPlayer實現(xiàn)基本的播放皆刺,暫停少辣,上一首,下一首羡蛾,調(diào)節(jié)音量漓帅,調(diào)節(jié)進度等,正在學習的新人可以看下痴怨,有什么不足可以互相學習忙干,謝謝支持
qq音樂.gif
這個是我寫的一個簡單的低仿QQ音樂, 如果你也喜歡聽音樂的話, 快來自己制作一個吧!
下面我們來實現(xiàn), 首先我們用單例寫的音樂管理器, 我把它命名為MusicManager:
. h
//
// MusicManager.h
// 22-QQ音樂MV
//
// Created by dllo on 16/8/19.
// Copyright ? 2016年 高雅馨. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface MusicManager : NSObject
@property (nonatomic, strong) NSMutableArray *musicArray;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, strong) AVPlayer *player;
// 分享信息
+ (instancetype)shareInfo;
// 播放和暫停
- (void)playAndPause;
// 上一首
- (void)playPrevious;
// 下一首
- (void)playNext;
- (void)replaceItemWithUrlString:(NSString *)urlString;
// 調(diào)節(jié)音量
- (void)playerVolumeWithVolumeFloat:(CGFloat)volumeFloat;
// 播放進度條
- (void)playerProgressWithProgressFloat:(CGFloat)progressFloat;
@end
. m
//
// MusicManager.m
// 22-QQ音樂MV
//
// Created by dllo on 16/8/19.
// Copyright ? 2016年 高雅馨. All rights reserved.
//
#import "MusicManager.h"
static MusicManager *_musicManager = nil;
@implementation MusicManager
+ (instancetype)shareInfo
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_musicManager = [[MusicManager alloc] init];
});
return _musicManager;
}
- (instancetype)init
{
if (self = [super init]) {
_player = [[AVPlayer alloc] init];
}
return self;
}
// 播放
- (void)playerPlay
{
[_player play];
_isPlay = YES;
}
- (void)playerPause
{
[_player pause];
_isPlay = NO;
}
- (void)playAndPause
{
if (self.isPlay) {
[self playerPause];
}else{
[self playerPlay];
}
}
- (void)playPrevious
{
if (self.index == 0) {
self.index = self.musicArray.count - 1;
}else{
self.index--;
}
}
- (void)playNext
{
if (self.index == self.musicArray.count - 1) {
self.index = 0;
}else{
self.index++;
}
}
- (void)playerVolumeWithVolumeFloat:(CGFloat)volumeFloat
{
self.player.volume = volumeFloat;
}
- (void)playerProgressWithProgressFloat:(CGFloat)progressFloat
{
[self.player seekToTime:CMTimeMakeWithSeconds(progressFloat, 1) completionHandler:^(BOOL finished) {
[self playerPlay];
}];
}
- (void)replaceItemWithUrlString:(NSString *)urlString
{
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:urlString]];
[self.player replaceCurrentItemWithPlayerItem:item];
[self playerPlay];
}
@end
這里呢, 類已經(jīng)封裝好, 拿過去就可以用哈??
在VC里, 我是在API里抓的接口, 用起來很方便的, 推薦給大家這個網(wǎng)址:https://www.showapi.com/api/apiList?search=qq
寫到這里也就差不多了, 下次會補充隨機模式的. 相信大家在調(diào)用時會很容易呢, 頁面也可以自己設(shè)計一下, (__) 嘻嘻……, 來實現(xiàn)吧, 很簡單吼!