iOS声音播放及音效处理开源代码_SoundManager

来源:互联网 发布:数据库系统教程王能斌 编辑:程序博客网 时间:2024/04/28 12:23

最近的一个项目中需要经常播放各种音效,这里是一个比较方便使用的class,用来播放声音文件

项目中需要包含AVFoundation和AudioToolbox两个Library

[html] view plaincopy
  1. SoundManager.h  
[html] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2. #import <AVFoundation/AVFoundation.h>  
  3.   
  4. @interface SoundManager : NSObject  
  5. {  
  6.     AVAudioPlayer *player;  
  7. }  
  8.   
  9. +(id) sharedManager;  
  10.   
  11. -(void) playSoundEffectWithFileName: (NSString *)fileName;  
  12.   
  13. @end  

[plain] view plaincopy
  1. SoundManager.m  
[plain] view plaincopy
  1. #import "SoundManager.h"  
  2. #import <AudioToolbox/AudioToolbox.h>  
  3.   
  4. static SoundManager *soundManagerInstance;  
  5.   
  6. @implementation SoundManager  
  7.   
  8. +(id) sharedManager  
  9. {  
  10.     if(!soundManagerInstance)  
  11.     {  
  12.         soundManagerInstance = [[LDCSoundManager alloc] init];  
  13.     }  
  14.     return soundManagerInstance;  
  15. }  
  16.   
  17. -(void)playSoundEffectWithFileName:(NSString *)fileName  
  18. {  
  19.     SystemSoundID _soundID;  
  20.     NSString *newMessageSoundPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];  
  21.     if(newMessageSoundPath)  
  22.     {  
  23.         NSURL *newMessageSoundUrl = [NSURL fileURLWithPath:newMessageSoundPath];  
  24.         OSStatus err = AudioServicesCreateSystemSoundID((CFURLRef)newMessageSoundUrl, &_soundID);  
  25.         if (err != kAudioServicesNoError)  
  26.         {  
  27.             //add  
  28.         }  
  29.         else  
  30.         {  
  31.             AudioServicesPlaySystemSound(_soundID);  
  32.         }  
  33.     }  
  34. }  
  35.   
  36. @end  

随后,在需要播放音效时引用这个类,并添加

[plain] view plaincopy
  1. [[SoundManager sharedManager] playSoundEffectWithFileName:@"YourSoundFileName"];  

即可