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

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

2013-08-02 14:24 471 查看
最近的一个项目中需要经常播放各种音效,这里是一个比较方便使用的class,用来播放声音文件

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

[html] view
plaincopy

SoundManager.h  

[html] view
plaincopy

#import <Foundation/Foundation.h>  

#import <AVFoundation/AVFoundation.h>  

  

@interface SoundManager : NSObject  

{  

    AVAudioPlayer *player;  

}  

  

+(id) sharedManager;  

  

-(void) playSoundEffectWithFileName: (NSString *)fileName;  

  

@end  

[plain] view
plaincopy

SoundManager.m  

[plain] view
plaincopy

#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  

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

[plain] view
plaincopy

[[SoundManager sharedManager] playSoundEffectWithFileName:@"YourSoundFileName"];  

即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: