UI音乐播放之入门篇AudioSerVicesPlay

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

-1- AuidoSerVices 常用于提示音的播放,该种音频具有以下四种特点:

1>长度一般不超过30秒,不需要对播放过程进行控制

2>不能循环播放,不能暂停

3>不能播放立体声

4>不能播放混音

-2-创建提示音频AuidoSerVices。。的准备工作

1.添加一个系统类库。audioToolbox.framework

2.导入头文件在viewController中 #import <AudioToolbox/AudioToolbox.h>

-3-提示音的几个常用方法:

1.获得音效文件的路径

NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav" withExtension:nil];

2.加载音效文件,得到对应的音效ID

SystemSoundID soundID = 0;

AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);

3.播放音效

AudioServicesPlaySystemSound(soundID);

4.音效播放的c语言函数

音效播放的函数都是基于c语言编写的,所以在使用的过程中要注意与oc方法使用的区别

加载音效文件

AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID *outSystemSoundID)

释放音效资源

AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)

播放音效

AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)

播放音效带点震动

AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)

-4-程序简单实现

#import"RootViewController.h"#import<AudioToolbox/AudioToolbox.h>@interfaceRootViewController ()@end@implementationRootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if(self) {//Custom initialization}returnself;

}- (void)viewDidLoad

{

[super viewDidLoad];

[self creatUIButton];

}-(void)creatUIButton{

UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];

btn.frame=CGRectMake(100,100,100,100);

btn.backgroundColor=[UIColor grayColor];

[btn setTitle:@"播放"forState:UIControlStateNormal];

[btn setTitleColor:[UIColor cyanColor ] forState:UIControlStateNormal];

[btn addTarget:self action:@selector(PRessBtn:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];

}-(void)pressBtn:(id)sender{//1.获取全路径 因为加载音效需要使用CFURLRef 来加载音乐,所以使用能和它相互转换的NSURL 来转换路径NSString * pathStr= [[NSBundle mainBundle]pathForResource:@"sound"ofType:@"wav"];

NSURL* url=[NSURL fileURLWithPath:pathStr];//2.创建音效ID 一个ID代表一个音效文件SystemSoundID SID;//3.将音乐文件与ID绑定 将url 强转 将sid与之绑定AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &SID);//4.播放音效AudioServicesPlayAlertSound(SID);//5.当我们需要在音效播放结束时取消该音效则需要使用以下方法 函数名固定AudioServicesAddSystemSoundCompletion(SID, nil, nil,finishSound, nil);

}//该函数为系统方法,函数名,参数固定,不能修改voidfinishSound(SystemSoundID SID,void*finish){//6.撤销SIDAudioServicesDisposeSystemSoundID(SID);

}

注意:点击播放,就可以播放音效文件

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航