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"];