iOS学习笔记

SystemSoundID(音效的播放)

2016-08-02  本文已影响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

上一篇下一篇

猜你喜欢

热点阅读