确保u有
#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"];
在你 - (无效)玩{}方法你有
YourAppDel *appDel = [UIApplication sharedApplication].delegate;
[appDel playSound:@"testSong.wav"];
enjoi
来源
2011-12-11 15:39:25
pmk
谢谢。它并没有真正解决我的问题,但它是一个优雅的解决方案。我认为这是它与我同时运行的AVAudioRecorder(某种VU Meter)相冲突的原因。所以我以此为解决方案,并将找出一个新问题。谢谢! – Snilleblixten