要给工程中添加音频,首先要导入音频的框架 avfoundation.framework
然后新建一个类继承于uiviewcontroller, 我这里就叫firstvc.
首先在 appdelegate.m中初始化根视图
#import "appdelegate.h"
#import "firstvc.h"
@implementation appdelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions
{
self.window = [[[uiwindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease];
// override point for customization after application launch.
firstvc *firstvc = [[firstvc alloc] init];
self.window.rootviewcontroller = firstvc;
[firstvc release];
self.window.backgroundcolor = [uicolor whitecolor];
[self.window makekeyandvisible];
return yes;
}
然后在firstvc.h中导入avfoundation框架
#import <uikit/uikit.h>
//要想使用封装好的音频类,导入框,导入类头文件,缺一不可;
#import <avfoundation/avfoundation.h>
@interface firstvc : uiviewcontroller<avaudioplayerdelegate>
{
avaudioplayer *avaudioplayer; //播放器player
uiprogressview *progressv; //播放进度
uislider *volumeslider; //声音控制
nstimer *timer; //监控音频播放进度
}
@end
然后在firstvc.m里的viewdidload方法里填写代码 你需要导入一个音频才可以播放 像添加图片一样,直接拖到工程里就可以了
- (void)viewdidload
{
[super viewdidload];
// do any additional setup after loading the view.
//初始化三个button
uibutton *button = [uibutton buttonwithtype:uibuttontyperoundedrect];
[button setframe:cgrectmake(100, 100, 60, 40)];
[button settitle:@"play" forstate:uicontrolstatenormal];
[button addtarget:self action:@selector(play) forcontrolevents:uicontroleventtouchupinside];
[self.view addsubview:button];
uibutton *button1 = [uibutton buttonwithtype:uibuttontyperoundedrect];
[button1 setframe:cgrectmake(100, 150, 60, 40)];
[button1 settitle:@"pause" forstate:uicontrolstatenormal];
[button1 addtarget:self action:@selector(pause) forcontrolevents:uicontroleventtouchupinside];
[self.view addsubview:button1];
uibutton *button2 = [uibutton buttonwithtype:uibuttontyperoundedrect];
[button2 setframe:cgrectmake(100, 200, 60, 40)];
[button2 settitle:@"stop" forstate:uicontrolstatenormal];
[button2 addtarget:self action:@selector(stop) forcontrolevents:uicontroleventtouchupinside];
[self.view addsubview:button2];
//从budle路径下读取音频文件 轻音乐 - 萨克斯回家 这个文件名是你的歌曲名字,mp3是你的音频格式
nsstring *string = [[nsbundle mainbundle] pathforresource:@"轻音乐 - 萨克斯回家" oftype:@"mp3"];
//把音频文件转换成url格式
nsurl *url = [nsurl fileurlwithpath:string];
//初始化音频类 并且添加播放文件
avaudioplayer = [[avaudioplayer alloc] initwithcontentsofurl:url error:nil];
//设置代理
avaudioplayer.delegate = self;
//设置初始音量大小
// avaudioplayer.volume = 1;
//设置音乐播放次数 -1为一直循环
avaudioplayer.numberofloops = -1;
//预播放
[avaudioplayer preparetoplay];
//初始化一个播放进度条
progressv = [[uiprogressview alloc] initwithframe:cgrectmake(20, 50, 200, 20)];
[self.view addsubview:progressv];
[progressv release];
//用nstimer来监控音频播放进度
timer = [nstimer scheduledtimerwithtimeinterval:0.1 target:self
selector:@selector(playprogress)
userinfo:nil repeats:yes];
//初始化音量控制
volumeslider = [[uislider alloc] initwithframe:cgrectmake(20, 70, 200, 20)];
[volumeslider addtarget:self action:@selector(volumechange)
forcontrolevents:uicontroleventvaluechanged];
//设置最小音量
volumeslider.minimumvalue = 0.0f;
//设置最大音量
volumeslider.maximumvalue = 10.0f;
//初始化音量为多少
volumeslider.value = 5.0f;
[self.view addsubview:volumeslider];
[volumeslider release];
//声音开关控件(静音)
uiswitch *swith = [[uiswitch alloc] initwithframe:cgrectmake(100, 20, 60, 40)];
[swith addtarget:self action:@selector(onoroff:) forcontrolevents:uicontroleventvaluechanged];
//默认状态为打开
swith.on = yes;
[self.view addsubview:swith];
[swith release];
}
相应的自定义方法代码如下
//播放
- (void)play
{
[avaudioplayer play];
}
//暂停
- (void)pause
{
[avaudioplayer pause];
}
//停止
- (void)stop
{
avaudioplayer.currenttime = 0; //当前播放时间设置为0
[avaudioplayer stop];
}
//播放进度条
- (void)playprogress
{
//通过音频播放时长的百分比,给progressview进行赋值;
progressv.progress = avaudioplayer.currenttime/avaudioplayer.duration;
}
//声音开关(是否静音)
- (void)onoroff:(uiswitch *)sender
{
avaudioplayer.volume = sender.on;
}
//播放音量控制
- (void)volumechange
{
avaudioplayer.volume = volumeslider.value;
}
//播放完成时调用的方法 (代理里的方法),需要设置代理才可以调用
- (void)audioplayerdidfinishplaying:(avaudioplayer *)player successfully:(bool)flag
{
[timer invalidate]; //nstimer暂停 invalidate 使...无效;
}
最后别忘了释放内存
- (void)dealloc
{
[avaudioplayer release];
[progressv release];
[volumeslider release];
[timer release];
[super dealloc];
}
当然,你也可以再定义一个uislider来控制播放进度.
最后运行起来的就是这个样子
如果想要播放网络音乐,那么遗憾的是ios中的avaudioplayer不支持边下边播,所以只能下载到本地再播放。
方法:
nsstring *urlstr = @"http://…………xxx.mp3";
nsurl *url = [[nsurl alloc]initwithstring:urlstr];
nsdata * audiodata = [nsdata datawithcontentsofurl:url];
//将数据保存到本地指定位置
nsstring *docdirpath = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0];
nsstring *filepath = [nsstring stringwithformat:@"%@/%@.mp3", docdirpath , @"temp"];
[audiodata writetofile:filepath atomically:yes];
//播放本地音乐
nsurl *fileurl = [nsurl fileurlwithpath:filepath];
player = [[avaudioplayer alloc] initwithcontentsofurl:fileurl error:nil];
[player play];
注意代码中的player是类的私有变量,因为在arc模式下如果定义局部变量,出了作用域后对象会被销毁。这个问题也是纠结了好久才搞明白。参见链接
当然也可以不保存文件,只是将player的构造方法改为用data实例化即可。
总结:
下面说一下我遇到的各种问题:
1、由于添加了all exception断点,导致每次都在初始化的时候自动断到,因为不是oc异常,又无异常信息显示。这时应该编辑断点,将其类型由all改为oc。这个异常并不会导致程序的崩溃,所以可以不作处理。
2、网上有的说不能播放,解决方案是应该在 appdelegate.m文件中的
application didfinishlaunchingwithoptions 添加这样一句代码:
[[avaudiosession sharedinstance]setcategory:avaudiosessioncategoryplaybackerror:nil];