我想说,创建一个“观察者”类来播放所有按钮都连接到的声音。我将在下面举一个例子,它是一个单例类。它是一时兴起写的,没有经过测试,但会给你一个想法。
//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];
}