示例名:SysSound (声音播放器)
功能:播放系统声音(声音文件)、警告声(声音文件+振动)、振动
FrameWork: AudioToolbox.framework
源码解释:
- 得到主程序束路径
- 得到声音文件:tap.aif路径
- 创建系统声音ID(以路径为参数,返回声音对象)
- 根据需要播放:系统声音、警告声、振动
核心代码:
1 - (void)viewDidLoad {
2 CFURLRef soundFileURLRef; // the URL for tap.aif
3 SystemSoundID soundFileObject; // the object representing the tap.aif
4
5 // Get the main bundle for the app
6 CFBundleRef mainBundle = CFBundleGetMainBundle ();
7
8 // Get the URL to the sound file to play
9 soundFileURLRef = CFBundleCopyResourceURL (
10 mainBundle,
11 CFSTR ("tap"),
12 CFSTR ("aif"),
13 NULL
14 );
15
16 // Create a system sound object representing the sound file
17 AudioServicesCreateSystemSoundID (
18 soundFileURLRef,
19 &soundFileObject
20 );
21
22 // 1. play system sound (tap.aif)
23 AudioServicesPlaySystemSound (soundFileObject);
24 // 2. play alert sound (tap.aif + vibrate)
25 AudioServicesPlayAlertSound (soundFileObject);
26 // 3. play vibrate sound (vibrate only)
27 AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
28 // 根据需要自行选择1.2.3
29 }
运行结果:
play system sound: 的~~~
play alert sound: 的~~~+子~~~(振动)
play vibrate sound: 子~~~(振动)