iOS调用手机振动或者音频文件

添加#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);
    
}


posted @ 2016-04-25 10:54  youngyi  阅读(688)  评论(0编辑  收藏  举报