最近想做一个关于电台的软件,所以翻看了一些音频播放的东西,当然,这个只是播放系统音效的,不会用来播放网络音乐,但是我封装了一下,希望对广大博友们有用!!!!!
.h文件为
<!-- lang: cpp -->
//
// PYAudioTool.h
// 01-音频播放
//
// Created by panyong on 14-6-25.
// Copyright (c) 2014年 itcast. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PYAudioTool : NSObject
+(void)playSound:(NSString *)soundFile;
+(void)disposeSound:(NSString *)soundFlie;
@end
.m文件内容为
//
// PYAudioTool.m // 01-音频播放 // // Created by panyong on 14-6-25. // Copyright (c) 2014年 itcast. All rights reserved. //
#import "PYAudioTool.h" #import <AVFoundation/AVFoundation.h>
@implementation PYAudioTool
static NSMutableDictionary *_soundIDDict;
+(void)initialize { _soundIDDict = [NSMutableDictionary dictionary]; }
+(void)playSound:(NSString *)soundFile { if (!soundFile) { return; } //创建SystemSoundID SystemSoundID soundID = [_soundIDDict[soundFile] unsignedLongValue]; if (!soundID) { NSURL *url = [[NSBundle mainBundle] URLForResource:soundFile withExtension:nil]; if (!url) { return; } AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID); _soundIDDict[soundFile] = @(soundID); } AudioServicesPlaySystemSound(soundID); }
+(void)disposeSound:(NSString *)soundFlie { if (!soundFlie) { return; } SystemSoundID soundID = [_soundIDDict[soundFlie] unsignedLongValue]; AudioServicesDisposeSystemSoundID(soundID); _soundIDDict[soundFlie] = nil;
} @end
我们只需要在用的时候,传入系统文件的文件名即可,当然,音效文件一定要在bundle中才行哦! 先导入头文件,#import "PYAudioTool.h" 下面是调用 [PYAudioTool playSound:@"buyao.wav"];
就这么简单,如果内存出现警告,可以调用销毁方法[PYAudioTool disposeSound:@"buyao.wav"];