ios程序播放音频文件

使用RYAVTool在Objective-C中播放音频文件
本文介绍了如何使用RYAVTool类在Objective-C中播放音频文件,包括初始化类实例、加载音频资源以及播放音频的方法。此外,文章还提供了解决内存泄漏问题的解决方案,通过清理缓存来释放不再使用的音频资源。

1.控制器代码

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

#import "RYAVTool.h"

 

@interface ViewController ()

 

@property(nonatomic,strong)NSMutableDictionary*allAvID;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

}

 

 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

   self.allAvID= [RYAVTool playAVWithName:@"m_06.wav"];

}

//内存警告时清理缓存

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    [self.allAvID enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

        AudioServicesDisposeSystemSoundID([obj unsignedIntValue]);

    }];

    

    

}

@end

 

2.辅助工具类代码

#import <Foundation/Foundation.h>

 

@interface RYAVTool : NSObject

 

+(NSMutableDictionary*)playAVWithName:(NSString*)name;

 

@end

 

#import "RYAVTool.h"

#import <AVFoundation/AVFoundation.h>

 

 

static NSMutableDictionary *_allID;

static SystemSoundID _currentData;

 

@implementation RYAVTool

 

+(void)load

{

    if (_allID==nil) {

        _allID =[[NSMutableDictionary alloc]init];

    }

}

 

+(NSMutableDictionary*)playAVWithName:(NSString*)name

{

    if (!name) {

        return _allID;

    }

    

    NSString*path=[[NSBundle mainBundle]pathForResource:name ofType:nil];

    if (!path) {

        return _allID;

    }

    NSURL *url=[NSURL fileURLWithPath:path];

    _currentData=[_allID[name] unsignedIntValue];

    if (!_currentData) {

        //创建音频播放文件

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

        //保存

        _allID[name]=@(_currentData);

    }

    //播放

    AudioServicesPlayAlertSound(_currentData);

    

    return _allID;

}

@end

转载于:https://www.cnblogs.com/tangranyang/p/4662504.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值