zoukankan      html  css  js  c++  java
  • ios 短音效的使用

    1.通用短音效ID的获取
    #import <Foundation/Foundation.h>
    
    @interface MJAudioTool : NSObject
    
    /**
     *  播放音效
     *
     *  @param filename 音效文件名
     */
    + (void)playSound:(NSString *)filename;
    
    /**
     *  销毁音效
     *
     *  @param filename 音效文件名
     */
    + (void)disposeSound:(NSString *)filename;
    @end
    
    #import "MJAudioTool.h"
    #import <AVFoundation/AVFoundation.h>
    
    @implementation MJAudioTool
    
    // 字典: filename作为key, soundID作为value
    // 存放所有的音频ID
    static NSMutableDictionary *_soundIDDict;
    + (void)initialize
    {
        _soundIDDict = [NSMutableDictionary dictionary];
    }
    
    + (void)playSound:(NSString *)filename
    {
        if (!filename) return;
        
        // 1.从字典中取出soundID
        SystemSoundID soundID = [_soundIDDict[filename] unsignedLongValue];
        if (!soundID) { // 创建
            // 加载音效文件
            NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
            
            if (!url) return;
            
            // 创建音效ID
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
            
            // 放入字典
            _soundIDDict[filename] = @(soundID);
        }
        
        // 2.播放
        AudioServicesPlaySystemSound(soundID);
    }
    
    + (void)disposeSound:(NSString *)filename
    {
        if (!filename) return;
        
        SystemSoundID soundID = [_soundIDDict[filename] unsignedLongValue];
        if (soundID) {
            // 销毁音效ID
            AudioServicesDisposeSystemSoundID(soundID);
            
            // 从字典中移除
            [_soundIDDict removeObjectForKey:filename];
        }
    }
    
    @end
    

     2.通用方法的使用

        [MJAudioTool playSound:@"buyao.wav"];

  • 相关阅读:
    2028 ACM Lowest Common Multiple Plus
    2032 杨辉三角
    2011 ACM 0和1思想
    grid
    Change position in observation
    1490 ACM 数学
    1489 ACM 贪心
    2009 ACM 水题
    Book Lending Registration
    MR1和MR2(Yarn)工作原理流程
  • 原文地址:https://www.cnblogs.com/fuunnyy/p/5196679.html
Copyright © 2011-2022 走看看