[关闭]
@kezhen 2015-12-15T00:09:27.000000Z 字数 4630 阅读 8530

iOS音频播放的几种方式

SystemSoundServices 后台音乐播放


一、使用AVAudioPlayer播放音乐

1. Background Modes

打开后台模式的音乐播放,或者在info.plist文件中添加Required Background Modes键,其值是App plays audio or streams audio/video using AirPlay

Background Modes

2. 添加后台播放代码

  1. AVAudioSession *session = [AVAudioSession sharedInstance];
  2. [session setActive:YES error:nil];
  3. [session setCategory:AVAudioSessionCategoryPlayback error:nil];

3. 播放指定的音频文件

  1. // 1.获取要播放音频文件的URL
  2. NSURL *fileURL = [[NSBundle mainBundle]URLForResource:@"王力宏-流泪手心" withExtension:@".mp3"];
  3. // 2.创建 AVAudioPlayer 对象
  4. self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
  5. // 3.打印歌曲信息
  6. NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%ld\n 音频文件持续时间:%g",self.audioPlayer.numberOfChannels,self.audioPlayer.duration];
  7. NSLog(@"%@",msg);
  8. // 4.设置循环播放
  9. self.audioPlayer.numberOfLoops = -1;
  10. self.audioPlayer.delegate = self;
  11. // 5.开始播放
  12. [self.audioplayer play];

二、使用System Sound Services播放音频

利用System Sound Services只能播放一些很小的提示或警告音频,它存在诸多限制,例如:声音长度不能超过30秒,不能控制进度,格式支持少等。

1. 注册音频文件

调用 AudioServicesCreateSystemSoundID(CFURLRef inFileURL,SystemSoundID *outSystemSoundID) 该函数的第一个参数代表音频文件的URL(可通过NSURL转换成CFURLRef),第二个参数代表注册音频文件的SystemSoundID。

2. 在音频播放完执行某些操作

调用AudioServicesAddSystemSoundCompletion()函数为制定SystemSoundID注册Callback函数。

3. 播放音频

调用AudioServicePlaySystemSound函数或者AudioServicePlayAlertSound(调用系统振动功能)。

4. 实战

  1. #import "FKViewController.h"
  2. static void completionCallback(SystemSoundID mySSID)
  3. {
  4. // Play again after sound play completion
  5. AudioServicesPlaySystemSound(mySSID);
  6. }
  7. @implementation ViewController
  8. // 音频文件的ID
  9. SystemSoundID ditaVoice;
  10. - (void)viewDidLoad
  11. {
  12. [super viewDidLoad];
  13. // 1. 定义要播放的音频文件的URL
  14. NSURL *voiceURL = [[NSBundle mainBundle]URLForResource:@"CleanDidFinish" withExtension:@"aiff"];
  15. // 2. 注册音频文件(第一个参数是音频文件的URL 第二个参数是音频文件的SystemSoundID)
  16. AudioServicesCreateSystemSoundID((__bridge CFURLRef)(voiceURL),&ditaVoice);
  17. // 3. 为crash播放完成绑定回调函数
  18. AudioServicesAddSystemSoundCompletion(ditaVoice,NULL,NULL,(void*)completionCallback,NULL);
  19. // 4. 播放 ditaVoice 注册的音频 并控制手机震动
  20. AudioServicesPlayAlertSound(ditaVoice);
  21. // AudioServicesPlaySystemSound(ditaVoice);
  22. // AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); // 控制手机振动
  23. }

使用System Sound Services需要AudioToolbox框架的支持,需要导入其主头文件:#import<AudioToolbox/AudioToolbox.h>


三、使用MPMusicPlayerController控制本机音乐播放

对控制内置音乐库播放状态以及媒体信息的获取进行了封装,主要用于公司手环端蓝牙发送指令控制手机音乐播放以及在手环荧幕上显示歌曲名称。
下面介绍一下用法:
1. 包含我封装的头文件 #import "BackgroundMusic.h"
2. 遵守协议:achieveMusicInfoDelegate
3. 初始化:

  1. @property (nonatomic,strong) BackgroundMusic *musicController;
  2. self.musicController = [[BackgroundMusic alloc]init];
  3. self.musicController.delegate = self; // 设置当前控制器为代理

4. 监听媒体曲目的改变:

  1. // 在 - (void)viewDidLoad 方法中调用以下方面
  2. [self.musicController monitorMediaItem];
  3. // 实现代理方法
  4. - (void)achieveachieveMusicInfo:(NSString *)songName andPlaybackStatus:(int)playStatus
  5. {
  6. if (1 == playStatus) {
  7. NSLog(@"正在播放音乐中...");
  8. }else if(0 == playStatus){
  9. NSLog(@"音乐暂停中...");
  10. }else{
  11. NSLog(@"播放状态未知...");
  12. }
  13. NSLog(@"歌曲信息:%@",songName);
  14. }

5. 播放控制

  1. // 控制音乐播放、暂停
  2. [self playOrPause];
  3. // 下一曲
  4. [self next];

1. 判断有没有正在播放的媒体项目

  1. if ([self.playController indexOfNowPlayingItem] == NSNotFound) {
  2. return YES;
  3. }else{
  4. return NO;
  5. }

2. 创建媒体队列

  1. /**
  2. * 设置媒体播放队列
  3. */
  4. - (void)createMediaQuery
  5. {
  6. // Creates a media query that matches music items and that groups and sorts collections by song name.
  7. self.query = [MPMediaQuery songsQuery];
  8. // Sets a music player’s playback queue based on a media query.
  9. [self.playController setQueueWithQuery:self.query];
  10. }

3. 获取正在播放的媒体曲目的信息

  1. @property (nonatomic, readonly) MPMediaEntityPersistentID
  2. @property (nonatomic, readonly) MPMediaType mediaType
  3. @property (nonatomic, readonly) NSString *title
  4. @property (nonatomic, readonly) NSString *albumTitle
  5. @property (nonatomic, readonly) MPMediaEntityPersistentID
  6. @property (nonatomic, readonly) NSString *artist
  7. @property (nonatomic, readonly) MPMediaEntityPersistentID
  8. @property (nonatomic, readonly) NSString *albumArtist
  9. ...
  1. /**
  2. * 获取媒体信息
  3. */
  4. - (void)obtainMusicInfo
  5. {
  6. MPMediaItem *currentItem = [self.playController nowPlayingItem];
  7. NSString *artist = [currentItem valueForProperty:MPMediaItemPropertyArtist];
  8. NSString *songName = [currentItem valueForProperty:MPMediaItemPropertyTitle];
  9. self.musicInfo = [NSString stringWithFormat:@"%@-%@",artist,songName];
  10. }

4. 监听播放媒体项目的通知

  1. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  2. [notificationCenter addObserver:self
  3. selector:@selector(updateMusicInfo)
  4. name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
  5. object:nil];
  6. [self.playController beginGeneratingPlaybackNotifications];
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注