2010-03-20 114 views
7

有沒有人有使用AudioToolBox框架,可以用來播放短聲的片段?如果您與我和其他社區分享,我將不勝感激。我看到的其他地方似乎都不太清楚他們的代碼。在iPhone SDK中播放聲音?

謝謝!

+0

有什麼特別的東西你要找? AV Foundation框架是播放聲音最簡單的方法,但我認爲你需要更多的東西? – 2010-03-20 16:43:15

+0

Nah,Id只是想知道播放短聲的標準方式......許多人圍繞着'網絡使用AudioToolBox ......感謝您的迴應:) – esqew 2010-03-20 16:56:54

回答

11

下面是使用AVAudioPlayer一個簡單的例子:

-(void)PlayClick 
{ 
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
               pathForResource:@"click" 
               ofType:@"caf"]]; 
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil]; 
    [click play]; 
    [click release]; 
} 

這假定了一個名爲「click.caf」,可以在主束文件。當我播放這個聲音很多時,我實際上會把它放在後面播放,而不是釋放它。

+0

它不適用於我。請幫助我 – 2012-07-17 03:56:36

+0

@VineeshTP您可能需要將名稱/類型更改爲您想要播放的文件。但是,我建議提出一個新問題,並詳細說明爲什麼它不適合你。 – 2012-07-17 15:53:12

+0

@NathanS .:我改變了文件的文件名。 – 2012-07-18 03:32:32

7

我寫了一個簡單的Objective-C的包裝圍繞AudioServicesPlaySystemSound,朋友們:

#import <AudioToolbox/AudioToolbox.h> 

/* 
    Trivial wrapper around system sound as provided 
    by Audio Services. Don’t forget to add the Audio 
    Toolbox framework. 
*/ 

@interface Sound : NSObject 
{ 
    SystemSoundID handle; 
} 

// Path is relative to the resources dir. 
- (id) initWithPath: (NSString*) path; 
- (void) play; 

@end 

@implementation Sound 

- (id) initWithPath: (NSString*) path 
{ 
    [super init]; 
    NSString *resourceDir = [[NSBundle mainBundle] resourcePath]; 
    NSString *fullPath = [resourceDir stringByAppendingPathComponent:path]; 
    NSURL *url = [NSURL fileURLWithPath:fullPath]; 

    OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle); 
    NSAssert1(errcode == 0, @"Failed to load sound: %@", path); 
    return self; 
} 

- (void) dealloc 
{ 
    AudioServicesDisposeSystemSoundID(handle); 
    [super dealloc]; 
} 

- (void) play 
{ 
    AudioServicesPlaySystemSound(handle); 
} 

@end 

生活here。有關其他聲音選項,請參閱this question

+1

我建議人們使用@ zoul的系統聲音解決方案(按鈕點擊等)。它支持更少的格式,但它應該滯後較少,並且這是用於系統聲音的首選記錄解決方案。另一方面,AVAudioPlayer非常適合播放音樂 - 但這不是原始海報的要求。 :-) – 2012-08-09 15:07:29

2

AudioServices - iPhone Developer Wiki

的AudioService聲音是不考慮該裝置體積控制器。即使手機處於靜音模式,也會播放音頻服務聲音。這些聲音只能通過設置 - >聲音 - >鈴聲和提醒

自定義系統聲音可以通過下面的代碼播放:

CFBundleRef mainbundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainbundle, CFSTR("tap"), CFSTR("aif"), NULL); 
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject); 

調用振動iPhone

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 

內置的播放系統聲音。

AudioServicesPlaySystemSound(1100);