#import "ViewController.h"
#import "ModalVC.h"
#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (assign, nonatomic) SystemSoundID soundID;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
ModalVC *modal = [[ModalVC alloc] init];
modal.createSoundIDBlock = ^ (SystemSoundID soundID) {
self.soundID = soundID;
};
[self presentViewController:modal animated:YES completion:nil];
}
- (IBAction)createBtnAction:(id)sender
{
NSURL *url = [[NSBundle mainBundle] URLForResource:@"xiaosheng.mp3" withExtension:nil];
CFURLRef cfUrl = CFBridgingRetain(url);
AudioServicesCreateSystemSoundID(cfUrl, &_soundID);
CFRelease(cfUrl);
}
- (IBAction)playBtnAction:(id)sender
{
NSURL *url = [[NSBundle mainBundle] URLForResource:@"xiaosheng.mp3" withExtension:nil];
[AudioTool playAudioWithURL:url];
}
- (IBAction)disposeBtnAction:(id)sender
{
[AudioTool disposeAll];
}
@end
#import <Foundation/Foundation.h>
@interface AudioTool : NSObject
/**
* 播放指定URL的音效文件
*
* @param url 音效文件的URL
*/
+ (void)playAudioWithURL:(NSURL *)url;
/**
* 销毁所有缓存的音效
*/
+ (void)disposeAll;
@end
#import "AudioTool.h"
#import <AVFoundation/AVFoundation.h>
/**
1. 负责管理所有音效的工具类, 类方法
2. 缓存, (NSDictionary: Key - Value), 使用URL作为Key, NSNumber(SoundID)作为Value
*/
static NSMutableDictionary *_cache;
@implementation AudioTool
+ (void)load
{
_cache = [NSMutableDictionary dictionary];
}
+ (void)playAudioWithURL:(NSURL *)url
{
if (url == nil) {
NSLog(@"URL不能为空");
return;
}
NSNumber *number = _cache[url];
if (number == nil) {
NSLog(@"创建了音效");
SystemSoundID soundID;
CFURLRef cfUrl = CFBridgingRetain(url);
AudioServicesCreateSystemSoundID(cfUrl, &soundID);
CFRelease(cfUrl);
number = [NSNumber numberWithUnsignedInt:soundID];
_cache[url] = number;
}
AudioServicesPlaySystemSound([number unsignedIntValue]);
}
+ (void)disposeAll
{
[_cache enumerateKeysAndObjectsUsingBlock:^(NSURL *key, NSNumber *obj, BOOL * _Nonnull stop) {
AudioServicesDisposeSystemSoundID([obj unsignedIntValue]);
}];
[_cache removeAllObjects];
}
@end
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ModalVC : UIViewController
@property (copy, nonatomic) void(^createSoundIDBlock)(SystemSoundID);
@end
#import "ModalVC.h"
@interface ModalVC ()
@end
@implementation ModalVC
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor redColor]];
CFURLRef url = CFBridgingRetain([[NSBundle mainBundle] URLForResource:@"win.aac" withExtension:nil]);
SystemSoundID soundID;
AudioServicesCreateSystemSoundID(url, &soundID);
CFRelease(url);
if (self.createSoundIDBlock) {
self.createSoundIDBlock(soundID);
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"我走了");
[self dismissViewControllerAnimated:YES completion:nil];
}
@end