美文网首页iOS学习笔记
SystemSoundID(音效的播放)

SystemSoundID(音效的播放)

作者: 学长的日常 | 来源:发表于2016-08-02 11:26 被阅读394次
    #import <Foundation/Foundation.h>
    
    @interface AudioTool : NSObject
    
    + (void)playSoundWithName:(NSString *)soundName;
    
    @end
    
    #import "AudioTool.h"
    #import <AVFoundation/AVFoundation.h>
    
    static NSMutableDictionary *_soundDict;
    
    @implementation AudioTool
    
    + (void)initialize{
        
        _soundDict = [NSMutableDictionary dictionary];
    }
    
    
    + (void)playSoundWithName:(NSString *)soundName{
        
        //1 从字典中取出对应的声音文件的soundID
        SystemSoundID soundId = [_soundDict[soundName]unsignedIntValue];
        //2 如果取出为空,则创建对应的音效文件
        if (soundId == 0) {
            
            //2.1 获取对应音频的URL
            CFURLRef urlRef = (__bridge CFURLRef)([[NSBundle mainBundle]URLForResource:soundName withExtension:nil]);
            
            //2.2创建对应的音效文件
            AudioServicesCreateSystemSoundID(urlRef, &soundId);
            
            //2.3存到字典中
            [_soundDict setObject:@(soundId) forKey:soundName];
            
        }
        
        //3 播放音效
        AudioServicesPlayAlertSound(soundId);
        
    }
    @end
    
    #import "ViewController.h"
    #import "AudioTool.h"
    @interface ViewController ()
    
    @end
    
    //播放三种音效的方法
    - (IBAction)buyao:(UIButton *)sender {
        
        [AudioTool playSoundWithName:@"buyao.wav"];
    }
    - (IBAction)bigKing:(UIButton *)sender {
        
        [AudioTool playSoundWithName:@"m_17.wav"];
    }
    - (IBAction)smallKing:(UIButton *)sender {
        
        [AudioTool playSoundWithName:@"m_16.wav"];
    }
    
    @end
    
    

    相关文章

      网友评论

        本文标题:SystemSoundID(音效的播放)

        本文链接:https://www.haomeiwen.com/subject/rbyfsttx.html