Убедитесь, что у вас есть
#import <AVFoundation/AVFoundation.h>
в заголовке.Тогда в вашем AppDelegate вы должны иметь следующие методы:
- (AVAudioPlayer *) getSound: (NSString *) soundName {
@try {
AVAudioPlayer *sound = [[self getDictionary] objectForKey: soundName];
if (!sound) {
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource: soundName ofType: nil];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath: path]
error: &error];
if (!sound) {
//NSLog(@"ERROR: Wrong sound format: %@. Description: %@", soundName, [error localizedDescription]);
} else {
sound.volume = 0.7;
//int len = sound.duration;
[[self getDictionary] setObject: sound forKey: soundName];
// NSLog(@"%@ loaded, duration: %i sec", soundName, len);
[sound release];
}
}
return sound;
}
@catch (id theException) {
NSLog(@"ERROR: %@ not found!", soundName);
}
return nil;
}
- (NSMutableDictionary *) getDictionary {
if (!dictionary) { //Hashtable
dictionary = [[NSMutableDictionary alloc] init];
NSLog(@"new Dictionary");
}
return dictionary;
}
- (void) playSound: (NSString *) soundName {
AVAudioPlayer *sound = [self getSound: soundName];
if (sound) {
sound.currentTime = 0;
if (!sound.playing) {
sound.numberOfLoops = 0;
[sound play];
}
}
}
- (void) stopSound: (NSString *) soundName {
AVAudioPlayer *sound = [self getSound: soundName];
if (sound && sound.playing) {
[sound stop];
}
}
В вашем AppDelegateDidFinishLaunching вы предварительно загрузите все звуки, которые будете использовать:
//pre-Load sounds
[self getSound: @"testSong.wav"];
В вашем - (void) методе play {}иметь
YourAppDel *appDel = [UIApplication sharedApplication].delegate;
[appDel playSound:@"testSong.wav"];
наслаждайтесь