天天看點

ios播放系統自帶音效以及震動

int systemsoundid;

audioservicesplaysystemsound(systemsoundid);

//systemsoundid的取值範圍在1000-2000

//播放自己的聲音,但此種播放方法主要播放一些較短的聲音檔案

nsstring *path = [nsstring stringwithformat:@"%@%@", [[nsbundle mainbundle] resourcepath], 

@"/jad0007a.wav"];

id systemsoundid soundid;

nsurl *filepath = [nsurl fileurlwithpath:path isdirectory:no];

audioservicescreatesystemsoundid((cfurlref)filepath, &soundid);

audioservicesplaysystemsound(soundid);

需求大緻分為三種:

1.震動

2.系統音效(無需提供音頻檔案)

3.自定義音效(需提供音頻檔案)

我的工具類的封裝:

[cpp] 

// 

//  wqplaysound.h 

//  wqsound 

//  created by 念茜 on 12-7-20. 

//  copyright (c) 2012年 __mycompanyname__. all rights reserved. 

#import <uikit/uikit.h> 

#import <audiotoolbox/audiotoolbox.h> 

@interface wqplaysound : nsobject 

    systemsoundid soundid; 

-(id)initforplayingvibrate; 

-(id)initforplayingsystemsoundeffectwith:(nsstring *)resourcename oftype:(nsstring *)type; 

-(id)initforplayingsoundeffectwith:(nsstring *)filename; 

-(void)play; 

@end 

[cpp]

//  wqplaysound.m 

#import "wqplaysound.h" 

@implementation wqplaysound 

-(id)initforplayingvibrate 

    self = [super init]; 

    if (self) { 

        soundid = ksystemsoundid_vibrate; 

    } 

    return self;     

-(id)initforplayingsystemsoundeffectwith:(nsstring *)resourcename oftype:(nsstring *)type 

        nsstring *path = [[nsbundle bundlewithidentifier:@"com.apple.uikit"] 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 

        nsurl *fileurl = [[nsbundle mainbundle] urlforresource:filename withextension:nil]; 

        if (fileurl != nil) 

        { 

            osstatus error = audioservicescreatesystemsoundid((__bridge cfurlref)fileurl, &thesoundid); 

            if (error == kaudioservicesnoerror){ 

-(void)play 

    audioservicesplaysystemsound(soundid); 

-(void)dealloc 

{  

    audioservicesdisposesystemsoundid(soundid); 

調用方法步驟:

1.加入audiotoolbox.framework到工程中

2.調用wqplaysound工具類

2.1震動

wqplaysound *sound = [[wqplaysound alloc]initforplayingvibrate]; 

[sound play]; 

2.2系統音效,以tock為例

wqplaysound *sound = [[wqplaysound alloc]initforplayingsystemsoundeffectwith:@"tock" oftype:@"aiff"]; 

2.3自定義音效,将tap.aif音頻檔案加入到工程

wqplaysound *sound = [[wqplaysound alloc]initforplayingsoundeffectwith:@"tap.aif"];