iOS 系统声音播放

    在iOS中可通过两种方式去播放声音:

            *  播放压缩的声音文件,比如mp3文件,一般使用播放声音中提到的方法,适用于播放时间较长,比如大于30秒,AVAudioPlayer可以提供更多的控制特性,比如暂停等等

            *   播放系统声音,比如翻页的哗啦声,应该使用播放系统声音的方法,因为压缩的声音文件比播放wav等非压缩声音文件在播放前消耗更多的处理器资源,这样的声音还要频繁的播放,而且,因为系统声音文件都较小,一般小于30秒,因此即使压缩格式,也不会节省多少存储空间。

    播放系统声音:首先要导入系统框架 <AudioToolbox/AudioToolbox.h>

                 

   

   播放系统声音,基本思路是:

      * 在播放前,比如控制器初始化阶段,注册系统声音,并保存一个系统声音id

      * 在需要播放系统声音的时候只需调用系统服务的全局方法,传入系统声音id即可

 

 在我们了解了基本思路后,就可以上代码了: 

+ (void)initSystemSoundWithName:(NSString *)soundName SoundType:(NSString *)soundType{
    [ZKAudioToolBox initAudioToolBox];
    if (audioTool) {
        //得到音频路径
        NSString *path=[NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",soundName,soundType];
        if (path) {
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&audioTool->sound);
            
            if (error != kAudioServicesNoError) {//获取的声音的时候,出现错误
                audioTool->sound=nil;
            }
            
            //获取自定义的声音
//            NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:soundName ofType:soundType]; //音乐文件路径
//            CFURLRef thesoundURL = (__bridge CFURLRef)[NSURL fileURLWithPath:thesoundFilePath];
//            AudioServicesCreateSystemSoundID(thesoundURL, &audioTool->sound);
            
            //开始播放声音
            AudioServicesPlaySystemSound(audioTool->sound);
        }
    }
}

  

  如上就能正常的播放声音了,写成单例的形式,就能便于多个页面调用!!!

原文地址:https://www.cnblogs.com/boyuanmeng/p/4208344.html