iOS开发,音效的播放简单实现以及音效播放的简单封装

一.音效的播放简单实现

iOS开发,音效的播放简单实现以及音效播放的简单封装

二.音效播放的封装 -- 封装思路:将生成的SystemSoundID存放到字典中,每次播放的时候从字典中取出对应的SystemSoundID,没有的话再创建

  • 头文件中定义类方法                                                                                   iOS开发,音效的播放简单实现以及音效播放的简单封装
  • 代码实现
    #import "ChaosAudioTool.h"
    #import <AVFoundation/AVFoundation.h>
    // 类方法中不能用成员属性,所以只能定义全局变量
    static NSMutableDictionary *_sounds;
    
    @implementation ChaosAudioTool
    
    // 懒加载字典
    + (void)initialize
    {
        _sounds = [NSMutableDictionary dictionary];
    }
    
    + (void)playAudioWithSoundName:(NSString *)soundName
    {
        if (_sounds[soundName] == nil) { // 先通过字典取,没有的话创建
            SystemSoundID soundID = 0;
            
            NSURL *url = [[NSBundle mainBundle] URLForResource:soundName withExtension:nil];
            
            AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
            
            // 存入集合
            _sounds[soundName] = @(soundID);
        }
        
        AudioServicesPlaySystemSound([_sounds[soundName] unsignedIntValue]);
    }