Objective-C简单的音乐播放器(边下边播)

时间:2023-02-10 15:23:52

Objective-C中的音乐播放大多用AVAudioPlayer,它有很多优点:
(1)可以播放任意长度音乐;
(2)可以循环播放;
(3)可以控制播放的时间;
(4)可以控制声道的音量实现立体声效果;
(5)可以调整音量。
但是AVAudioPlayer有一个很大的缺点,那就是只能用于播放本地音频,网络资源播放之前必须先加载,不能立即播放;但系统为我们提供了另一个更为丰富的类MPMoviePlayerController和AVPlayer来播放流媒体,MPMoviePlayerController使用更简单,但功能不如AVPlayer强大。这里介绍一下AVPlayer播放在线音频,播放视频以后再介绍。直接上代码,注释会尽量写的详细一些:
新建一个类继承自NSObject:AudioPlayer
.h文件代码:

#import <Foundation/Foundation.h>
@class AudioPlayer;

@protocol AudioPlayerDelegate <NSObject>

//再播放中每秒都执行的事件
- (void)audioplayerPlayWith:(AudioPlayer *)audioplayer Progress:(float)progress;

//当一首歌曲播放完成之后执行这个事件
- (void)audioplayerDidFinishItem:(AudioPlayer *)audioplayer;

@end


@interface AudioPlayer : NSObject


@property(nonatomic,assign)id<AudioPlayerDelegate>delegate;
@property(nonatomic,assign)BOOL isPlaying;
+(AudioPlayer*)sharePlayer;
-(void)play;
-(void)pause;
-(void)seekToTime:(float)time;
-(void)setPrepareMusicUrl:(NSString*)urlStr;
@end

.m文件代码:

#import "AudioPlayer.h"
@import AVFoundation;
@interface AudioPlayer ()
{
BOOL _isPrepare;//播放是否准备成功
BOOL _isPlaying;//播放器是否正在播放
}

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)NSTimer *timer;

@end
@implementation AudioPlayer

+(AudioPlayer*)sharePlayer
{

static AudioPlayer *player = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
player = [AudioPlayer new];
});
return player;
}
- (instancetype)init
{
self = [super init];
if (self) {
//通知中心
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
return self;
}

-(void)setPrepareMusicUrl:(NSString*)urlStr
{

if (self.player.currentItem) {
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
}

//创建一个item资源
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:urlStr]];
[item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
[self.player replaceCurrentItemWithPlayerItem:item];
}

-(void)play
{
//判断资源是否准备成功
if (!_isPrepare) {
return;
}
[self.player play];
_isPlaying = YES;
//播放时候的图片转动效果
//timer初始化
if (_timer) {
return;
}

//创建一个timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playingAction:) userInfo:nil repeats:YES];


}
-(void)pause
{
if (!_isPlaying) {
return;
}

[self.player pause];
_isPlaying = NO;
//销毁计时器
[_timer invalidate];
_timer = nil;

}

-(void)seekToTime:(float)time
{

//当音乐播放器时间改变时,先暂停后播放
[self pause];
[self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
if (finished) {
[self play];
}
}];

}
//每隔0.1秒执行一下这个事件
-(void)playingAction:(id)sender
{


if (self.delegate&&[self.delegate respondsToSelector:@selector(audioplayerPlayWith:Progress:)]) {

//获取当前播放歌曲的时间
float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
[self.delegate audioplayerPlayWith:self Progress:progress];


}

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

AVPlayerStatus staute = [change[@"new"] integerValue];
switch (staute) {
case AVPlayerStatusReadyToPlay:
NSLog(@"加载成功,可以播放了");
_isPrepare = YES;
[self play];
break;
case AVPlayerStatusFailed:
NSLog(@"加载失败");
break;
case AVPlayerStatusUnknown:
NSLog(@"资源找不到");
break;


default:
break;
}

NSLog(@"change:%@",change);
}
//当一首歌播放结束时会执行下面的方法
-(void)endAction:(NSNotification *)not
{

if (self.delegate &&[self.delegate respondsToSelector:@selector(audioplayerDidFinishItem:)]) {
[self.delegate audioplayerDidFinishItem:self];
}

}

-(AVPlayer*)player
{
if (_player==nil) {
_player = [AVPlayer new];
}
return _player;
}

-(BOOL)isPlaying{
return _isPlaying;
}
@end

使用方法很简单,传正确的url初始化然后调用对应的方法,我就不玩滚这里粘贴了。此外推荐一个第三方库AFSoundManager, 简化了 iOS 音频播放功能,支持本地文件和流媒体,通过一个完全 Block 驱动的 Objective-C 类实现。使用 AudioToolbox 和 AVFoundation 框架。我在Demo中也对其进行了封装。用法和我们刚刚封装的AudioPlayer类似。感兴趣的可以看看。
demo:
Objective-C简单的音乐播放器(边下边播)
GitHub:https://github.com/FEverStar/AudioDemo