iOS App中實(shí)現(xiàn)播放音效和音樂功能的簡單示例
播放音效
iOS開發(fā)過程中可能會(huì)遇到播放音效的功能
其實(shí)很簡單,iOS已經(jīng)提供了一個(gè)框架直接負(fù)責(zé)播放音效 AudioToolbox.framework
新建項(xiàng)目 TestWeChatSounds
給新建的項(xiàng)目導(dǎo)入AudioToolbox.framework
導(dǎo)入成功之后如下圖
項(xiàng)目目錄如下
接下來我們給項(xiàng)目中添加幾個(gè)caf格式的音效文件
接下來 我們打開 項(xiàng)目默認(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:@"錯(cuò)誤" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(btn2Act) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
}
實(shí)現(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ù)會(huì)將音效文件加入到系統(tǒng)音頻服務(wù)中并返回一個(gè)長整形ID)
*/
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
//如果需要在播放完之后執(zhí)行某些操作,可以調(diào)用如下方法注冊一個(gè)播放完成回調(diào)函數(shù)
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallback, NULL);
//2.播放音頻
AudioServicesPlaySystemSound(soundID);//播放音效
// AudioServicesPlayAlertSound(soundID);//播放音效并震動(dòng)
}
void soundCompleteCallback(SystemSoundID soundID,voidvoid * clientData){
NSLog(@"播放完成...");
}
代碼部分截圖
好了播放音效基本實(shí)現(xiàn) 。
播放音樂
我們同樣使用蘋果提供的框架 AVFoundation.framework
首先,新建項(xiàng)目
給項(xiàng)目起名: TestAVGoundation
接下來導(dǎo)入framework
導(dǎo)入成功之后如下
項(xiàng)目結(jié)構(gòu)
開始寫代碼之前,我們找一首歌曲放到項(xiàng)目中
這里我們放一首比較經(jīng)典的歌曲 周華健的 朋友
同樣我們還是打開項(xiàng)目默認(rèn)生成的ViewController.m 在里面添加播放功能
首先,導(dǎo)入頭文件
#import <AVFoundation/AVFoundation.h>
接下來,創(chuàng)建個(gè)控件
@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)度更新定時(shí)器
初始化界面
- (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];
}
添加幾個(gè)播放,暫停,修改歌曲進(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ù)只能時(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ā)生錯(cuò)誤,錯(cuò)誤信息:%@",error.localizedDescription);
return nil;
}
}
return _audioPlayer;
}
/**
* 播放音頻
*/
-(void)play{
if (![self.audioPlayer isPlaying]) {
[self.audioPlayer play];
self.timer.fireDate=[NSDate distantPast];//恢復(fù)定時(shí)器
}
}
/**
* 暫停播放
*/
-(void)pause{
if ([self.audioPlayer isPlaying]) {
[self.audioPlayer pause];
self.timer.fireDate=[NSDate distantFuture];//暫停定時(shí)器,注意不能調(diào)用invalidate方法,此方法會(huì)取消,之后無法恢復(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)音樂暫停了 再次打開 又接著播放了
如果想要后臺 也可以接著播放音樂 我們需要修改兩個(gè)地方
1,打開項(xiàng)目 plist 文件
添加一項(xiàng)
2,打開ViewController.m 找到如下方法 添加一段
好了 試下后臺運(yùn)行吧~
- 講解iOS開發(fā)中對音效和音樂播放的簡單實(shí)現(xiàn)
- 實(shí)例解析iOS中音樂播放器應(yīng)用開發(fā)的基本要點(diǎn)
- iOS開發(fā)中音頻工具類的封裝以及音樂播放器的細(xì)節(jié)控制
- iOS實(shí)現(xiàn)播放遠(yuǎn)程網(wǎng)絡(luò)音樂的核心技術(shù)點(diǎn)總結(jié)
- ios開發(fā):一個(gè)音樂播放器的設(shè)計(jì)與實(shí)現(xiàn)案例
- iOS利用AVPlayer播放網(wǎng)絡(luò)音樂的方法教程
- iOS中關(guān)于音樂鎖屏控制音樂(鎖屏信息設(shè)置)的實(shí)例代碼
- iOS視頻添加背景音樂同時(shí)保留原音
- 運(yùn)用iOS教你輕松制作音樂播放器
- iOS實(shí)現(xiàn)獲取系統(tǒng)iTunes音樂的方法示例
相關(guān)文章
iOS進(jìn)階之xib上控件自動(dòng)生成純代碼
本篇內(nèi)容是一篇關(guān)于IOS開發(fā)進(jìn)階的內(nèi)容,學(xué)習(xí)xib上控件自動(dòng)生成純代碼這個(gè)功能,有興趣的朋友參考下。2018-02-02iOS 圖片上傳使用base64或者二進(jìn)制流上傳頭像功能
這篇文章主要介紹了iOS 圖片上傳使用base64或者二進(jìn)制流上傳頭像功能,需要的朋友可以參考下2017-09-09iOS中UITableView Cell實(shí)現(xiàn)自定義單選功能
本篇文章主要介紹了iOS中UITableView Cell實(shí)現(xiàn)自定義單選功能,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02iOS 委托與文本輸入(內(nèi)容根據(jù)iOS編程編寫)
這篇文章主要介紹了iOS 委托與文本輸入(內(nèi)容根據(jù)iOS編程編寫) 的相關(guān)資料,需要的朋友可以參考下2016-09-09關(guān)于iOS屏幕旋轉(zhuǎn)的一些注意事項(xiàng)
這篇文章主要給大家介紹了關(guān)于iOS屏幕旋轉(zhuǎn)的一些注意事項(xiàng),文中通過一步步的步驟介紹的很詳細(xì),相信對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,有需要的朋友可以參考學(xué)習(xí),下面來一起看看吧。2017-01-01總結(jié)iOS開發(fā)中的斷點(diǎn)續(xù)傳與實(shí)踐
本文先從斷點(diǎn)續(xù)傳問題開始,介紹斷點(diǎn)續(xù)傳概述和原理。接著結(jié)合筆者調(diào)研中嘗試的 AFHTTPRequestOpeartion,簡單分析源碼。最后分別基于 NSURLConnection,NSURLSessionDataTask 和 NSURLSessionDownloadTask 去實(shí)現(xiàn)應(yīng)用重啟情況下的斷點(diǎn)續(xù)傳。下面一起來看看。2016-07-07iOS動(dòng)畫解析之圓球加載動(dòng)畫XLBallLoading的實(shí)現(xiàn)
加載動(dòng)畫對大家來說都不陌生,我們在平時(shí)都會(huì)遇見,開發(fā)中也必不可少,所以下面這篇文章主要給大家介紹了關(guān)于iOS動(dòng)畫解析之圓球加載動(dòng)畫XLBallLoading實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-11-11