OS sdk中提供了很多方便的方法来播放多媒体。本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件。
AudioToolbox framework
使用AudioToolbox framework。这个框架可以将比较短的声音注册到 system sound服务上。被注册到system sound服务上的声音称之为 system sounds。它必须满足下面几个条件。
1、 播放的时间不能超过30秒
2、数据必须是 PCM或者IMA4流格式
3、必须被打包成下面三个格式之一:Core Audio Format (.caf), Waveform audio (.wav), 或者 Audio Interchange File (.aiff)
声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:
#import <AudioToolbox/AudioToolbox.h>
@interface MediaPlayerViewController : UIViewController
{
IBOutlet UIButton *audioButton;
SystemSoundID shortSound;
}
- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];
if (self) {
// Get the full path of Sound12.aif
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"
ofType:@"aif"];
// If this file is actually in the bundle...
if (soundPath) {
// Create a file URL with this path
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
// Register sound file located at that URL as a system sound
OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)soundURL,
&shortSound);
if (err != kAudioServicesNoError)
NSLog(@"Could not load %@, error code: %d", soundURL, err);
}
}
return self;
}
这样就可以使用下面代码播放声音了:
- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
}
使用下面代码,还加一个震动的效果:
- (IBAction)playShortSound:(id)sender
{
AudioServicesPlaySystemSound(shortSound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
AVFoundation framework
对于压缩过Audio文件,或者超过30秒的音频文件,可以使用AVAudioPlayer类。这个类定义在AVFoundation framework中。
下面我们使用这个类播放一个mp3的音频文件。首先要引入AVFoundation framework,然后MediaPlayerViewController.h中添加下面代码:
#import <AVFoundation/AVFoundation.h>
@interface MediaPl