这个链接非常详尽地列举了IOS7里面所有的系统声音,声音的ID,声音的存放位置
尽管现在已经是ios8的时代,但是系统声音这个东东不会因此过时,毕竟声音就那几十种,不会一下子有太大变化。
https://github.com/TUNER88/iOSSystemSoundsLibrary
这个stackoverflow里面有一些比较有用的信息和链接,包括怎样播放系统声音,怎样查看ref
http://stackoverflow.com/questions/7831671/playing-system-sound-without-importing-your-own
还有一个很凶残的github项目,他把所有.framework都放上去,供大家下载。其中有我刚好需要的audiotoolbox
https://github.com/EthanArbuckle/IOS-7-Headers
这个博客教怎么使用系统封装好的API
http://www.cnblogs.com/martin1009/archive/2012/06/14/2549473.html
假如要做一个模块,要求能够在系统需要的地方播放短暂的音效,那么就可以写以下这么一个类,用上单例模式,让其全局可用。
关于单例,我也写过一篇简单的介绍,在此不做介绍。当然,不使用单例模式也是完全没问题的。
// CHAudioPlayer.h
// Created by HuangCharlie on 3/26/15.
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "SynthesizeSingleton.h"
@interface CHAudioPlayer : NSObject
{
}
DEF_SINGLETON_FOR_CLASS(CHAudioPlayer);
// play system vibration of device
-(void)updateWithVibration;
//play system sound with id, more detail in system sound list
// system sound list at:
// https://github.com/TUNER88/iOSSystemSoundsLibrary
// check for certain sound if needed
-(void)updateWithSoundID:(SystemSoundID)soundId;
// play resource sound, need to import resource into project
-(void)updateWithResource:(NSString*)resourceName ofType:(NSString*)type;
// action of play
-(void)play;
@end
// CHAudioPlayer.m
// Created by HuangCharlie on 3/26/15.
#import "CHAudioPlayer.h"
@interface CHAudioPlayer()
@property (nonatomic,assign) SystemSoundID soundID;
@end
@implementation CHAudioPlayer
IMPL_SINGLETON_FOR_CLASS(CHAudioPlayer);
//vibration
-(void)updateWithVibration
{
self.soundID = kSystemSoundID_Vibrate;
}
-(void)updateWithSoundID:(SystemSoundID)soundId
{
self.soundID = soundId;
}
//sound of imported resouces, like wav
-(void)updateWithResource:(NSString*)resourceName ofType:(NSString*)type
{
[self dispose];
NSString *path = [[NSBundle mainBundle] pathForResource:resourceName ofType:type];
if (path) {
//注册声音到系统
NSURL* url = [NSURL fileURLWithPath:path];
CFURLRef inFileURL = (__bridge CFURLRef)url;
SystemSoundID tempSoundId;
OSStatus error = AudioServicesCreateSystemSoundID(inFileURL, &tempSoundId);
if(error == kAudioServicesNoError)
self.soundID = tempSoundId;
}
}
-(void)play
{
AudioServicesPlaySystemSound(self.soundID);
}
-(void)dispose
{
AudioServicesDisposeSystemSoundID(self.soundID);
}
@end
这里有一个地方十分要注意!
如果要使用自己的资源来播放的话,会使用到updateWithResource.
其中,下面的那两行代码如果写成分开的,就没有什么问题。如果写到一起,很可能会因为异步的原因或者其他原因造成crash。故要分开写如下。
//注册声音到系统
NSURL* url = [NSURL fileURLWithPath:path];
CFURLRef inFileURL = (__bridge CFURLRef)url;
具体使用就很简单了。在需要注册声音的地方使用update。。。在播放的地方使用 play