最近的一个项目中需要经常播放各种音效,这里是一个比较方便使用的class,用来播放声音文件
项目中需要包含AVFoundation和AudioToolbox两个Library
- SoundManager.h
- #import <Foundation/Foundation.h>
- #import <AVFoundation/AVFoundation.h>
- @interface SoundManager : NSObject
- {
- AVAudioPlayer *player;
- }
- +(id) sharedManager;
- -(void) playSoundEffectWithFileName: (NSString *)fileName;
- @end
- SoundManager.m
- #import "SoundManager.h"
- #import <AudioToolbox/AudioToolbox.h>
- static SoundManager *soundManagerInstance;
- @implementation SoundManager
- +(id) sharedManager
- {
- if(!soundManagerInstance)
- {
- soundManagerInstance = [[LDCSoundManager alloc] init];
- }
- return soundManagerInstance;
- }
- -(void)playSoundEffectWithFileName:(NSString *)fileName
- {
- SystemSoundID _soundID;
- NSString *newMessageSoundPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
- if(newMessageSoundPath)
- {
- NSURL *newMessageSoundUrl = [NSURL fileURLWithPath:newMessageSoundPath];
- OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)newMessageSoundUrl, &_soundID);
- if (err != kAudioServicesNoError)
- {
- //add
- }
- else
- {
- AudioServicesPlaySystemSound(_soundID);
- }
- }
- }
- @end
随后,在需要播放音效时引用这个类,并添加
- [[SoundManager sharedManager] playSoundEffectWithFileName:@"YourSoundFileName"];
即可