如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
OSsdk中提供了很多方便的方法来播放多媒体。本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件。AudioToolboxframework使用AudioToolboxframework。这个框架可以将比较短的声音注册到systemsound服务上。被注册到systemsound服务上的声音称之为systemsounds。它必须满足下面几个条件。1、播放的时间不能超过30秒2、数据必须是PCM或者IMA4流格式3、必须被打包成下面三个格式之一:CoreAudioFormat(.caf),Waveformaudio(.wav),或者AudioInterchangeFile(.aiff)声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:#import<AudioToolbox/AudioToolbox.h>@interfaceMediaPlayerViewController:UIViewController{IBOutletUIButton*audioButton;SystemSoundIDshortSound;}-(id)init{self=[superinitWithNibName:@"MediaPlayerViewController"bundle:nil];if(self){//GetthefullpathofSound12.aifNSString*soundPath=[[NSBundlemainBundle]pathForResource:@"Sound12"ofType:@"aif"];//Ifthisfileisactuallyinthebundle...if(soundPath){//CreateafileURLwiththispathNSURL*soundURL=[NSURLfileURLWithPath:soundPath];//RegistersoundfilelocatedatthatURLasasystemsoundOSStatuserr=AudioServicesCreateSystemSoundID((CFURLRef)soundURL,&shortSound);if(err!=kAudioServicesNoError)NSLog(@"Couldnotload%@,errorcode:%d",soundURL,err);}}returnself;}这样就可以使用下面代码播放声音了:-(IBAction)playShortSound:(id)sender{AudioServicesPlaySystemSound(shortSound);}使用下面代码,还加一个震动的效果:-(IBAction)playShortSound:(id)sender{AudioServicesPlaySystemSound(shortSound);AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);}AVFoundationframework对于压缩过Audio文件,或者超过30秒的音频文件,可以使用AVAudioPlayer类。这个类定义在AVFoundationframework中。下面我们使用这个类播放一个mp3的音频文件。首先要引入AVFoundationframework,然后MediaPlayerViewController.h中添加下面代码:#import<AVFoundation/AVFoundation.h>@interfaceMediaPlayerViewController:UIViewController<AVAudioPlayerDelegate>{IBOutletUIButton*audioButton;SystemSoundIDshortSound;AVAudioPlayer*audioPlayer;AVAudioPlayer类也是需要知道音频文件的路径,使用下面代码创建一个AVAudioPlayer实例:-(id)init{self=[superinitWithNibName:@"MediaPlayerViewController"bundle:nil];if(self){NSString*musicPath=[[NSBundlemainBundle]pathForResource:@"Music"ofType:@"mp3"];if(musicPath){NSURL*musicURL