您的位置:首页 > 移动开发 > IOS开发

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

2015-09-09 08:01 246 查看
//为了更好更方便的使用 这里封装了一个工具类,拿到哪里都可以使用
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: