ios-音频播放-短视频加载-封装工具类

//为了更好更方便的使用 这里封装了一个工具类,拿到哪里都可以使用
#import <Foundation/Foundation.h>

@interface AudioTool : NSObject
/**
 *
 *
 *  @param filename <#filename description#>
 */
+(void)playSound:(NSString *)filename;
/**
 *  <#Description#>
 *
 *  @param filename <#filename description#>
 */
+(void)disposeSound:(NSString *)filename;

@end
#import "AudioTool.h"
#import<AVFoundation/AVFoundation.h>
//工具类

@implementation AudioTool

//字典 filename:key soudID 作为value

static  NSMutableDictionary *_soundIDDict;

+(void)initialize
{
    _soundIDDict = [NSMutableDictionary dictionary];
}

+(void)playSound:(NSString *)filename
{
   //1.从字典中取出soundID
    if(!filename)return;
    
    SystemSoundID soundID = [_soundIDDict[filename] unsignedIntValue];
    if (!soundID) {
    //加载音效文件
            NSURL *url = [[NSBundle mainBundle]URLForResource:filename withExtension:nil];
        if (!url) {
            return;
        }
        //创建音效ID
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url),&soundID);
        _soundIDDict[filename] = @(soundID);
    }
    //播放
    AudioServicesPlaySystemSound(soundID);

}


+(void)disposeSound:(NSString *)filename
{
    if(!filename)return;
    SystemSoundID soundID = [_soundIDDict[filename] unsignedIntValue];
    if (soundID) {
        //销毁音效ID
        Au

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "AudioTool.h"

@interface ViewController ()

//@property(nonatomic,assign)SystemSoundID soundID;

@end

@implementation ViewController

//-(SystemSoundID)soundID
//{
//    if (!_soundID) {
//        NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_03.wav" withExtension:nil];
//        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &_soundID);
//    }
//    return _soundID;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //1.加载音效文件(段音频)
    //1个音效文件 对应一个SoundID
//    SystemSoundID soundID;
//    
//    NSURL *url = [[NSBundle mainBundle]URLForResource:@"m_03.wav" withExtension:nil];
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
    //2.播放 拿到音效ID
 //   AudioServicesPlaySystemSound(self.soundID);
    NSString *filename = [NSString stringWithFormat:@"m_%02d.wav",arc4random_uniform(14)+3];
    [AudioTool playSound:filename];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
//    AudioServicesDisposeSystemSoundID(self.soundID);
//    self.soundID = 0;
    [AudioTool disposeSound:@"m_03.wav"];
    // Dispose of any resources that can be recreated.
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值