すべてのボタンが接続されているサウンドを再生する「オブザーバー」クラスを作成します。以下に例を示します。これはシングルトン クラスです。気まぐれに書かれており、テストされていませんが、アイデアが得られます。
//SoundObserver.h
#include <AVFoundation/AVFoundation.h>
@interface SoundObserver {
AVAudioPlayer *audioPlayer;
}
-(void)playSound;
+(SoundObserver*)sharedInstance;
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
@end
//SoundObserver.m
static SoundObserver *instance = nil;
@implementation SoundObserver
-(id)init {
self = [super init];
if(self) {
//Get path to file.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"sound"
ofType:@"wav"];
// filePath to URL
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
//Initialize the AVAudioPlayer.
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:fileURL error:nil];
// Preloads buffer and prepare for use.
[self.audioPlayer prepareToPlay];
[filePath release];
[fileURL release];
}
}
+(SoundObserver*)sharedInstance {
@synchronized(self) {
if (instance == nil)
instance = [[self alloc] init];
}
return instance;
}
-(void)playSound {
//make sure the audio resets to beginning each activation.
[self.audioPlayer play];
}
-(void)dealloc {
//Clean up
[self.audioPlayer release];
self.audioPlayer = nil;
[super dealloc];
}
// User example.
In applicationDidFinishLaunching:
[SoundObserver sharedInstance];
From here you can connect all buttons to the same function, or call it from anywhere in the App that #import's SoundObserver.h
-(IBOutlet)buttonClick:(id)sender {
[[SoundObserver sharedInstance] playSound];
}