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

时间:2021-11-25 15:47:26
//为了更好更方便的使用 这里封装了一个工具类,拿到哪里都可以使用
#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 作为valuestatic  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