播放音效 iOS

//

//  LKAudioTool.h

//  01-音效播放

//

//  Created by KwokLenny on 15/7/9.

//  Copyright (c) 2015 LK. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface LKAudioTool : NSObject

// 播放音效

// 传入需要 播放的音效文件名称

+ (void)playAudioWithFilename:(NSString  *)filename;


// 销毁音效

+ (void)disposeAudioWithFilename:(NSString  *)filename;

@end




//

//  LKAudioTool.m

//  01-音效播放

//

//  Created by KwokLenny on 15/7/9.

//  Copyright (c) 2015 LK. All rights reserved.

//


#import "LKAudioTool.h"

#import <AVFoundation/AVFoundation.h>

static NSMutableDictionary *_soundIDs;

@implementation LKAudioTool

+ (NSMutableDictionary *)soundIDs

{

    if (!_soundIDs) {

        _soundIDs = [NSMutableDictionarydictionary];

    }

    return _soundIDs;

}

+ (void)playAudioWithFilename:(NSString*)filename

{

    /*

     // -1.创建URL

     NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];

     

     // 0.创建音效ID

     SystemSoundID soundID;

     AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);

     

     // 1.播放音效(本地音效)

     #warning ios8的模拟器不支持播放音效(真机可以)

     AudioServicesPlaySystemSound(soundID);

     */

    // 0.判断文件名是否为nil

    if (filename == nil) {

        return;

    }

    

    // 1.从字典中取出音效ID

    SystemSoundID soundID = [[self soundIDs][filename] unsignedIntValue];

    

    // 判断音效ID是否为nil

    if (!soundID) {

        // 音效IDnil

        // 根据文件名称加载音效URL

        NSURL *url = [[NSBundle mainBundle]URLForResource:filename withExtension:nil];

        

        // 判断url是否为nil

        if (!url) {

            return;

        }

        

        // 创建音效ID

       AudioServicesCreateSystemSoundID((__bridgeCFURLRef)(url), &soundID);

        

        // 将音效ID添加到字典中

        [self soundIDs][filename] = @(soundID);

    }

    // 播放音效

    AudioServicesPlaySystemSound(soundID);

}


+ (void)disposeAudioWithFilename:(NSString*)filename

{

    // 0.判断文件名是否为nil

    if (filename == nil) {

        return;

    }

    

    // 1.从字典中取出音效ID

    SystemSoundID soundID = [[self soundIDs][filename] unsignedIntValue];

    

    if (soundID) {

        // 2.销毁音效ID

       AudioServicesDisposeSystemSoundID(soundID);

        

        // 3.从字典中移除已经销毁的音效ID

        [[self soundIDs]removeObjectForKey:filename];

    }

    

}


@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值