iOS App中實現(xiàn)播放音效和音樂功能的簡單示例
播放音效
iOS開發(fā)過程中可能會遇到播放音效的功能
其實很簡單,iOS已經(jīng)提供了一個框架直接負(fù)責(zé)播放音效 AudioToolbox.framework
新建項目 TestWeChatSounds


給新建的項目導(dǎo)入AudioToolbox.framework


導(dǎo)入成功之后如下圖

項目目錄如下

接下來我們給項目中添加幾個caf格式的音效文件

接下來 我們打開 項目默認(rèn)生成的ViewController中添加代碼
導(dǎo)入 AudioToolbox
#import <AudioToolbox/AudioToolbox.h>
給View上添加button點(diǎn)擊之后播放音效
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *btn1=[[UIButton alloc] initWithFrame:CGRectMake(20, 100, 120, 36)];
[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn1 setTitle:@"警告" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(btn1Act) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
UIButton *btn2=[[UIButton alloc] initWithFrame:CGRectMake(20, 150, 120, 36)];
[btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn2 setTitle:@"錯誤" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(btn2Act) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
}
實現(xiàn)播放效果
-(void)btn1Act {
[self playSoundEffect:@"alarm.caf"];
}
-(void)btn2Act {
[self playSoundEffect:@"ct-error.caf"];
}
-(void)playSoundEffect:(NSString *)name{
NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:nil];
NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
//1.獲得系統(tǒng)聲音ID
SystemSoundID soundID=0;
/**
* inFileUrl:音頻文件url
* outSystemSoundID:聲音id(此函數(shù)會將音效文件加入到系統(tǒng)音頻服務(wù)中并返回一個長整形ID)
*/
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
//如果需要在播放完之后執(zhí)行某些操作,可以調(diào)用如下方法注冊一個播放完成回調(diào)函數(shù)
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
//2.播放音頻
AudioServicesPlaySystemSound(soundID);//播放音效
// AudioServicesPlayAlertSound(soundID);//播放音效并震動
}
void soundCompleteCallback(SystemSoundID soundID,voidvoid * clientData){
NSLog(@"播放完成...");
}
代碼部分截圖

好了播放音效基本實現(xiàn) 。
播放音樂
我們同樣使用蘋果提供的框架 AVFoundation.framework
首先,新建項目

給項目起名: TestAVGoundation

接下來導(dǎo)入framework

導(dǎo)入成功之后如下

項目結(jié)構(gòu)

開始寫代碼之前,我們找一首歌曲放到項目中
這里我們放一首比較經(jīng)典的歌曲 周華健的 朋友

同樣我們還是打開項目默認(rèn)生成的ViewController.m 在里面添加播放功能
首先,導(dǎo)入頭文件
#import <AVFoundation/AVFoundation.h>
接下來,創(chuàng)建個控件
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器
@property (strong, nonatomic) UIProgressView *playProgress;//播放進(jìn)度
@property (strong, nonatomic) UIButton *playOrPause; //播放/暫停按鈕(如果tag為0認(rèn)為是暫停狀態(tài),1是播放狀態(tài))
@property (strong ,nonatomic) NSTimer *timer;//進(jìn)度更新定時器
初始化界面
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor=[UIColor lightGrayColor];
[self initUserFace];
}
-(void)initUserFace{
//添加playProgress
_playProgress= [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];
_playProgress.frame=CGRectMake(0, 100, self.view.bounds.size.width, 36);
[self.view addSubview:_playProgress];
//添加播放按鈕
_playOrPause=[[UIButton alloc]initWithFrame:CGRectMake(0, 150, 120, 36)];
[_playOrPause setTitle:@"播放" forState:UIControlStateNormal];
[_playOrPause setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_playOrPause addTarget:self action:@selector(playOrPauseAct:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_playOrPause];
}
添加幾個播放,暫停,修改歌曲進(jìn)度條顯示的方法
-(NSTimer *)timer{
if (!_timer) {
_timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
}
return _timer;
}
-(AVAudioPlayer *)audioPlayer{
if (!_audioPlayer) {
NSString *urlStr=[[NSBundle mainBundle]pathForResource:@"朋友.mp3" ofType:nil];
NSURL *url=[NSURL fileURLWithPath:urlStr];
NSError *error=nil;
//初始化播放器,注意這里的Url參數(shù)只能時文件路徑,不支持HTTP Url
_audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
//設(shè)置播放器屬性
_audioPlayer.numberOfLoops=0;//設(shè)置為0不循環(huán)
_audioPlayer.delegate=self;
[_audioPlayer prepareToPlay];//加載音頻文件到緩存
if(error){
NSLog(@"初始化播放器過程發(fā)生錯誤,錯誤信息:%@",error.localizedDescription);
return nil;
}
}
return _audioPlayer;
}
/**
* 播放音頻
*/
-(void)play{
if (![self.audioPlayer isPlaying]) {
[self.audioPlayer play];
self.timer.fireDate=[NSDate distantPast];//恢復(fù)定時器
}
}
/**
* 暫停播放
*/
-(void)pause{
if ([self.audioPlayer isPlaying]) {
[self.audioPlayer pause];
self.timer.fireDate=[NSDate distantFuture];//暫停定時器,注意不能調(diào)用invalidate方法,此方法會取消,之后無法恢復(fù)
}
}
/**
* 更新播放進(jìn)度
*/
-(void)updateProgress{
float progress= self.audioPlayer.currentTime /self.audioPlayer.duration;
[self.playProgress setProgress:progress animated:true];
}
#pragma mark - 播放器代理方法
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@"音樂播放完成...");
[_playOrPause setTitle:@"播放" forState:UIControlStateNormal];
}
我們給播放按鈕添加點(diǎn)擊事件
-(void)playOrPauseAct:(UIButton *)sender{
NSString *strPlay=sender.titleLabel.text;
NSLog(@"strPlay=%@",strPlay);
if ([strPlay isEqualToString:@"播放"]) {
[sender setTitle:@"暫停" forState:UIControlStateNormal];
[self play];
}else{
[sender setTitle:@"播放" forState:UIControlStateNormal];
[self pause];
}
}
好了,到此 我們創(chuàng)建完成 可以運(yùn)行試試
仔細(xì)的朋友可能發(fā)現(xiàn)我們的app播放音樂的過程中 如果切換到后臺之后發(fā)現(xiàn)音樂暫停了 再次打開 又接著播放了
如果想要后臺 也可以接著播放音樂 我們需要修改兩個地方
1,打開項目 plist 文件

添加一項

2,打開ViewController.m 找到如下方法 添加一段

好了 試下后臺運(yùn)行吧~
- 講解iOS開發(fā)中對音效和音樂播放的簡單實現(xiàn)
- 實例解析iOS中音樂播放器應(yīng)用開發(fā)的基本要點(diǎn)
- iOS開發(fā)中音頻工具類的封裝以及音樂播放器的細(xì)節(jié)控制
- iOS實現(xiàn)播放遠(yuǎn)程網(wǎng)絡(luò)音樂的核心技術(shù)點(diǎn)總結(jié)
- ios開發(fā):一個音樂播放器的設(shè)計與實現(xiàn)案例
- iOS利用AVPlayer播放網(wǎng)絡(luò)音樂的方法教程
- iOS中關(guān)于音樂鎖屏控制音樂(鎖屏信息設(shè)置)的實例代碼
- iOS視頻添加背景音樂同時保留原音
- 運(yùn)用iOS教你輕松制作音樂播放器
- iOS實現(xiàn)獲取系統(tǒng)iTunes音樂的方法示例
相關(guān)文章
iOS8調(diào)用相機(jī)報警告Snapshotting a view的解決方法
這篇文章主要介紹了iOS8調(diào)用相機(jī)報警告Snapshotting a view……的解決方法 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
阿里數(shù)據(jù)iOS端啟動速度優(yōu)化心得
本篇文章給大家詳細(xì)分析了阿里數(shù)據(jù)iOS端啟動速度優(yōu)化的知識點(diǎn)以及心得,對此有興趣的朋友參考學(xué)習(xí)下吧。2018-02-02
深入講解iOS開發(fā)中應(yīng)用數(shù)據(jù)的存儲方式
這篇文章主要介紹了iOS開發(fā)中應(yīng)用數(shù)據(jù)的存儲方式,包括plistXML屬性列表和NSKeydeArchiver歸檔兩個部分,需要的朋友可以參考下2015-12-12

