添加#import <AVFoundation/AVFoundation.h>

.h

{
    
    SystemSoundID soundID;
    
}

//播放振动效果的初始化
-(id)initForPlayingVibrate;

//播放音效的初始化
//@param resourceName 系统音效名称
//@param type 系统音效类型

-(id)initForPlayingSystemSoundEffectWith:(NSString *)resourceName ofType:(NSString *)type;
//为播放特定的音频文件初始化(需提供音频文件)
//@param filename 音频文件名(加在工程中)
-(id)initForPlayingSoundEffectWith:(NSString *)filename;

//播放音效
-(void)play;

 

 

 

.m

-(id)initForPlayingVibrate
{
    
    self = [super init];
    
    if (self) {
        
        soundID = kSystemSoundID_Vibrate;
        
    }
    
    return self;
}

-(id)initForPlayingSystemSoundEffectWith:(NSString *)resourceName ofType:(NSString *)type

{
    
    self = [super init];
    
    if (self) {
        
        NSString *path = [[NSBundle bundleWithIdentifier:@”da.-22″] pathForResource:resourceName ofType:type];
        
        if (path) {
            
            SystemSoundID theSoundID;
            
            OSStatus error =  AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &theSoundID);
            
            if (error == kAudioServicesNoError) {
                
                soundID = theSoundID;
                
            }else {
                NSLog(@”Failed to create sound “);
            }
            
        }
    }
    
    return self;
    
}

-(id)initForPlayingSoundEffectWith:(NSString *)filename

{
    
    self = [super init];
    
    if (self) {
        
        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
        
        if (fileURL != nil)
            
        {
            
            SystemSoundID theSoundID;
            
            OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID);
            
            if (error == kAudioServicesNoError){
                
                soundID = theSoundID;
                
            }else {
                
                NSLog(@”Failed to create sound “);
                
            }
            
        }
        
    }
    
    return self;
    
}

-(void)play

{
    AudioServicesPlaySystemSound(soundID);
}
-(void)dealloc
{
    AudioServicesDisposeSystemSoundID(soundID);
    
}

版权声明:本文为youngyi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/youngyi/p/5430141.html