对于简单的、无混音音频,
AVAudio ToolBox
框架提供了一个简单的
C
语言风格的音频服务。你可以使用
AudioservicesPlaySystemSound
函数来播放简单的声音。要遵守以下几个规则:
1. 音频长度小于 30 秒
2. 格式只能是 PCM 或者 IMA4
3. 文件必须被存储为 .caf 、 .aif 或者 .wav 格式
4. 简单音频不能从内存播放,而是只能是硬盘文件
除了对简单音频的限制外,你对音频播放的方式也基本无法控制。一旦音频播放就会立即开始,而且是当前电话使用者设置的音量播放。你将无法循环播放声音,也无法控制立体声效果。不过你还是可以设置一个回调函数,在音频播放结束的时候被调用,这样你就可以对音频对象做清理工作,以及通知你的程序播放结束。
1. #import <AudioToolbox/AudioToolbox.h>
2. #import <CoreFoundation/CoreFoundation.h>
3. // 当音频播放完毕会调用这个函数
4. static void SoundFinished(SystemSoundID soundID,void* sample){
5. /* 播放全部结束,因此释放所有资源 */
6. AudioServicesDisposeSystemSoundID(sample);
7. CFRelease(sample);
8. CFRunLoopStop(CFRunLoopGetCurrent());
9. }
10. // 主循环
11. int main(){
12. /* 系统音频 ID ,用来注册我们将要播放的声音 */
13. SystemSoundID soundID;
14. NSURL* sample = [[NSURL alloc]initWithString:@"sample.wav"];
15.
16. OSStatus err = AudioServicesCreateSystemSoundID(sample, &soundID);
17. if (err) {
18. NSLog(@"Error occurred assigning system sound!");
19. return -1;
20. }
21. /* 添加音频结束时的回调 */
22. AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, SoundFinished,sample);
23. /* 开始播放 */
24. AudioServicesPlaySystemSound(soundID);
25. CFRunLoopRun();
26. return 0;
27. }
1. 音频长度小于 30 秒
2. 格式只能是 PCM 或者 IMA4
3. 文件必须被存储为 .caf 、 .aif 或者 .wav 格式
4. 简单音频不能从内存播放,而是只能是硬盘文件
除了对简单音频的限制外,你对音频播放的方式也基本无法控制。一旦音频播放就会立即开始,而且是当前电话使用者设置的音量播放。你将无法循环播放声音,也无法控制立体声效果。不过你还是可以设置一个回调函数,在音频播放结束的时候被调用,这样你就可以对音频对象做清理工作,以及通知你的程序播放结束。
1. #import <AudioToolbox/AudioToolbox.h>
2. #import <CoreFoundation/CoreFoundation.h>
3. // 当音频播放完毕会调用这个函数
4. static void SoundFinished(SystemSoundID soundID,void* sample){
5. /* 播放全部结束,因此释放所有资源 */
6. AudioServicesDisposeSystemSoundID(sample);
7. CFRelease(sample);
8. CFRunLoopStop(CFRunLoopGetCurrent());
9. }
10. // 主循环
11. int main(){
12. /* 系统音频 ID ,用来注册我们将要播放的声音 */
13. SystemSoundID soundID;
14. NSURL* sample = [[NSURL alloc]initWithString:@"sample.wav"];
15.
16. OSStatus err = AudioServicesCreateSystemSoundID(sample, &soundID);
17. if (err) {
18. NSLog(@"Error occurred assigning system sound!");
19. return -1;
20. }
21. /* 添加音频结束时的回调 */
22. AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, SoundFinished,sample);
23. /* 开始播放 */
24. AudioServicesPlaySystemSound(soundID);
25. CFRunLoopRun();
26. return 0;
27. }