AVFoundation-AudioPlay-Group多个播放器同时播放实现炫酷电音节奏

任何人和事都有一个开始认识,逐渐提高,深入理解,全面掌握,随心所用的过程。本人初次自学音视频相关,如有不足还请各位大神指正,话不多说,进入主题:

该小应用可以实现三个播放器同步播放,并通过调节各自的播放速率和音量来呈现你想要的节奏。是不是有点炫酷哦!

1.搭建界面

2.创建播放器类

JWDPlayerController.h

#import

#import

@interfaceJWDPlayerController :NSObject

@property(nonatomic,readonly,getter=isPlaying)BOOLplaying;

- (void)play;

- (void)stop;

- (void)adjustRate:(CGFloat)rate forPlayerAtIndex:(NSInteger)index;;//控制播放速率

- (void)adjustPan:(CGFloat)pan ;/*调节声道权重set panning. -1.0 is left, 0.0

is center, 1.0 is right. */

- (void)adjustVolume:(CGFloat)volume forPlayerAtIndex:(NSInteger)index;//音量

@end

JWDPlayerController.m

#import"JWDPlayerController.h"

#import

@interfaceJWDPlayerController()

@property(nonatomic,assign)BOOLplaying;

@property(nonatomic,strong)NSArray*players;

@end

@implementationJWDPlayerController

- (instancetype)init {

self= [superinit];

if(self){

AVAudioPlayer*guitarplayer = [selfplayerWithFileName:@"guitar"];

AVAudioPlayer*bassplayer = [selfplayerWithFileName:@"bass"];

AVAudioPlayer*drumplayer = [selfplayerWithFileName:@"drums"];

_players=@[guitarplayer,drumplayer,bassplayer];

}

return

self;

}

- (AVAudioPlayer*)playerWithFileName:(NSString*)fileName {

NSURL*fileURL = [[NSBundlebundleForClass:[selfclass]]URLForResource:fileNamewithExtension:@"caf"];

NSError*error;

AVAudioPlayer*audioPlayer = [[AVAudioPlayeralloc]initWithContentsOfURL:fileURLerror:&error];

if(audioPlayer) {

audioPlayer.numberOfLoops= -1;//无限循环播放

audioPlayer.enableRate=YES;//设置为YES可以控制播放速率

[audioPlayerprepareToPlay];

returnaudioPlayer;

}else{

NSLog(@"创建播放器出错error: %@",[errorlocalizedDescription]);

return nil;

}

}

/**

播放

播放要对三个播放器同步,获取当前设备的时间,加一个小延时,然后遍历播放器数组里面的播放器,通过[player playAtTime:delayTime];设置起始播放时间,这样三个播放器就能精密的同步播放了。

*/

- (void)play {

if(!self.playing) {

NSTimeIntervaldelayTime = [self.players[0]deviceCurrentTime]+0.01;

for(AVAudioPlayer*playerin self.players){

[playerplayAtTime:delayTime];

}

self.playing=YES;

}

}

/**

停止

如果三个播放器都在播放,遍历去停止播放,并且player.currentTime = 0.0f;让播放进度回到音频文件的原点。

*/

- (void)stop {

if(self.playing) {

for(AVAudioPlayer*playerin self.players){

[playerstop];

player.currentTime=0.0f;

}

self.playing=NO;

}

}

//速率,在不改变音调的前提下,改变速率

- (void)adjustRate:(CGFloat)rateforPlayerAtIndex:(NSInteger)index;{

if([selfisValidIndex:index]){

AVAudioPlayer*player =self.players[index];

player.rate= rate;

}

}

/*调节声道权重set panning. -1.0 is left, 0.0 is center, 1.0

is right. */

- (void)adjustPan:(CGFloat)pan {

for(AVAudioPlayer*playerin self.players){

player.pan= pan;

}

}

//音量

- (void)adjustVolume:(CGFloat)volumeforPlayerAtIndex:(NSInteger)index {

if([selfisValidIndex:index]){

AVAudioPlayer*player =self.players[index];

player.volume= volume;

}

}

//防止数组越界

- (BOOL)isValidIndex:(NSUInteger)index{

returnindex ==0|| index

}

@end

在ViewController.m处理相应的事件

#import"ViewController.h"

#import"JWDPlayerController.h"

@interfaceViewController()

@property(nonatomic,strong)JWDPlayerController*playerController;//!< <#value#>

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

self.playerController= [[JWDPlayerControlleralloc]init];

}

//播放

- (IBAction)paly {

NSLog(@"播放");

[self.playerControllerplay];

}

//暂停

- (IBAction)stop {

NSLog(@"暂停");

[self.playerControllerstop];

}

//速率

- (IBAction)changeRate:(UISlider*)sender {

NSLog(@"改变速率-sender %f -- tag %ld",sender.value,(long)sender.tag);

[self.playerControlleradjustRate:sender.valueforPlayerAtIndex:sender.tag];

}

//音量

- (IBAction)changeVolume:(UISlider*)sender {

NSLog(@"改变音量-sender %f -- tag %ld",sender.value,(long)sender.tag);

[self.playerControlleradjustVolume:sender.valueforPlayerAtIndex:sender.tag];

}

//声道权衡

- (IBAction)pan:(UISlider*)sender {

NSLog(@"改变声道比重-sender %f -- tag %ld",sender.value,(long)sender.tag);

[self.playerControlleradjustPan:sender.value];

}

@end

********************************************华丽的分割线*******************************************

截止以上逻辑,就可以实现多个播放器同时播放,控制不同的音量、速率、声道等功能。但是如果作为一个专门播放音频类的应用,以上还是不够的,还需要进行一下的配置。

配置音频会话

测试一

在设备上运行程序,当播放时,切换“铃声/静音”开关,会有两种状态的切换。

测试二

在播放的同时按下Lock按钮,会有声音逐渐消失的现象。

作为以播放音频为核心功能的应用,不能允许以上情况出现。

解决

解决问题一方法:

在AppDelegate中

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

AVAudioSession*session = [AVAudioSessionsharedInstance];

NSError*error;

//指定音频会话分类

BOOLisSessionCategory = [sessionsetCategory:AVAudioSessionCategoryPlaybackerror:&error];

if(!isSessionCategory) {

NSLog(@"AVAudioSession

setCategory:error: %@",[errorlocalizedDescription]);

}

//设置为yes激活会话

BOOLisSessionActive = [sessionsetActive:YESerror:&error];

if(!isSessionActive) {

NSLog(@"AVAudioSession

setActive:error: %@",[errorlocalizedDescription]);

}

return YES;

}

注:

在获得一个AVAudioSession类的实例后,你就能通过调用音频会话对象的setCategory:error:实例方法,来从IOS应用可用的不同类别中作出选择。下面列出了可供使用的音频会话类别:

AVAudioSessionCategorySoloAmbient

这个类别非常像AVAudioSessionCategoryAmbient类别,除了会停止其他程序的音频回放。当设备被设置为静音模式,你的音频回放将会停止。

AVAudioSessionCategoryRecord

这会停止其他应用的声音并让你的应用也不能初始化音频回放(比如AVAudioPlayer)。在这种模式下,你只能进行录音。使用这个类别,调用AVAudioPlayer的prepareToPlay会返回YES,但是调用play方法将返回NO。主UI界面会照常工作。这时,即使你的设备屏幕被用户锁定了,应用的录音仍会继续。

AVAudioSessionCategoryPlayback

这个类别会静止其他应用的音频回放。你可以使用AVAudioPlayer的prepareToPlay和play方法,在你的应用中播放声音。主UI界面会照常工作。这时,即使屏幕被锁定或者设备为静音模式,音频回放都会继续。

AVAudioSessionCategoryPlayAndRecord

这个类别允许你的应用中同时进行声音的播放和录制。当你的声音录制或播放开始后,其他应用的声音播放将会停止。主UI界面会照常工作。这时,即使屏幕被锁定或者设备为静音模式,音频回放和录制都会继续。

AVAudioSessionCategoryAudioProcessing

这个类别用于应用中进行音频处理的情形,而不是音频回放或录制。设置了这种模式,你在应用中就不能播放和录制任何声音。调用AVAPlayer的prepareToPlay和play方法都将返回NO。其他应用的音频回放,比如iPod,也会在此模式下停止。

AVAudioSessionCategoryAmbient

这个类别不会停止其他应用的声音,相反,它允许你的音频播放于其他应用的声音之上,比如iPod。你的应用的主UI线程会工作正常。调用AVAPlayer的prepareToPlay和play方法都将返回YES。当用户锁屏时,你的应用将停止所有正在回放的音频。仅当你的应用是唯一播放该音频文件的应用时,静音模式将停止你程序的音频回放。如果正当iPod播放一手歌时,你开始播放音频,将设备设为静音模式并不能停止你的音频回放。

解决问题二方法:

设置info.plist

也可以这样设置

UIBackgroundModes

audio

添加完以后再次运行,按下lock键,依然会听到音乐播放。感觉像练成了降龙十八掌,太棒啦!

********************************************华丽的分割线*******************************************

处理中断事件

当我们正在播放音频时,如果突然来电话,那么我们播放的音乐会停止,当电话结束时,播放的音乐不会再次自动播放,那么就必须处理中断事件。

在出现中断之前,需要知道 中断事件的通知,注册通知

- (instancetype)init {

self= [superinit];

if(self){

AVAudioPlayer*guitarplayer = [selfplayerWithFileName:@"guitar"];

AVAudioPlayer*bassplayer = [selfplayerWithFileName:@"bass"];

AVAudioPlayer*drumplayer = [selfplayerWithFileName:@"drums"];

_players=@[guitarplayer,drumplayer,bassplayer];

//注册中断事件的通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleInterrRuption:)name:AVAudioSessionInterruptionNotificationobject:[AVAudioSessionsharedInstance]];

}

return

self;

}

- (void)handleInterrRuption:(NSNotification*)notification {

NSDictionary*info =

notification.userInfo;

AVAudioSessionInterruptionTypetype = [info[AVAudioSessionInterruptionTypeKey]unsignedIntegerValue];

if(type ==AVAudioSessionInterruptionTypeBegan) {//开始中断

[selfstop];

}else{//中断结束

AVAudioSessionInterruptionOptionsoptions = [info[AVAudioSessionInterruptionOptionKey]unsignedIntegerValue];

if(options ==AVAudioSessionInterruptionOptionShouldResume) {

[selfplay];

}

}

}

********************************************华丽的分割线*******************************************

截止以上代码,还是有小瑕疵,当插入耳机或者外界音频输出设备时,会在外界设备上播放,当断开外界设备时,音频播放有回到手机内置扬声器播放。根据苹果隐私问题,当插入耳机播放后,表示用户不愿意让别人听到在播放什么,所以当拔下耳机的时候,需要停止播放,保护用户的隐私。

在JWDPlayerController.m 中 祖册通知

- (instancetype)init {

self= [superinit];

if(self){

AVAudioPlayer*guitarplayer = [selfplayerWithFileName:@"guitar"];

AVAudioPlayer*bassplayer = [selfplayerWithFileName:@"bass"];

AVAudioPlayer*drumplayer = [selfplayerWithFileName:@"drums"];

_players=@[guitarplayer,drumplayer,bassplayer];

//注册中断事件的通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleInterruption:)name:AVAudioSessionInterruptionNotificationobject:[AVAudioSessionsharedInstance]];

//注册保护用户隐私的通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleRouteChange:)name:AVAudioSessionRouteChangeNotificationobject:[AVAudioSessionsharedInstance]];

}

return

self;

}

- (void)handleRouteChange:(NSNotification*)notification {

NSDictionary*info =

notification.userInfo;

NSLog(@"info--%@",info);

AVAudioSessionRouteChangeReasonreason = [info[AVAudioSessionRouteChangeReasonKey]unsignedIntegerValue];

if(reason ==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {

AVAudioSessionRouteDescription*description = info[AVAudioSessionRouteChangePreviousRouteKey];

AVAudioSessionPortDescription*portDescription = description.outputs[0];

NSString*portType = portDescription.portType;

if([portTypeisEqualToString:AVAudioSessionPortHeadphones]){

[selfstop];

}

}

}

在接到通知之后,判断是否有线路发送变化。

if(reason ==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {}

知道有设备断开后,需要向userinfo字典提出请求,获取前一个线路的AVAudioSessionRouteDescription

线路的描述 保存在一个数组中,元素为AVAudioSessionPortDescription用于描述不同接口的I/O接口属性。需要从线路描述中找到第一个输出接口并判断是否为耳机。然后入停止播放。

好了。截止现在,以音频播放为核心功能的应用,应该做出的基本问题完成。

千山过后尽开颜,万里长征第一步。本人以前接触的音视频相关方面较少,现想系统学习,由于是自学,可能有不足之处,如你发现,还请不吝赐教。谢谢!

符demo地址:https://github.com/weidongjiang/AVFoundation-AudioPlay-Group.git

如果帮助你解决了你的问题,或者你觉得还可以,那就给小弟一个star,一起共同学习。谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容