[英]No sound in iPhone app after pressing home button
我的聲音在模擬器中運行正常,但是當我在手機上運行應用程序時,按下主頁按鈕然后返回應用程序后聲音停止工作。 這是在IOS5中。 我怎么解決這個問題? AVAudioPlayer的委托事情似乎也停止了。 該應用程序不會崩潰。
NSString *path = [[NSBundle mainBundle]
pathForResource:@"Beep01" ofType:@"wav"];
clickSound =[[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:NULL];
clickSound.delegate = self;
[clickSound prepareToPlay];
后來我用[clickSound play]播放它;
確保你有
#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"];
enjoi
當您的應用程序轉到后台(或時鍾鬧鍾響起,或手機接到電話或屏幕鎖定)時,應用程序的音頻會話中斷,您的音頻播放器暫停。 處理此中斷的推薦方法是在音頻播放器的委托中實現AVAudioPlayerDelegate方法– audioPlayerBeginInterruption:
和-audioPlayerEndInterruption:
來自Apple的文檔 :
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
if (playing) {
playing = NO;
interruptedOnPlayback = YES;
[self updateUserInterface];
}
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
if (interruptedOnPlayback) {
[player prepareToPlay];
[player play];
playing = YES;
interruptedOnPlayback = NO;
}
}
請注意,當-audioPlayerEndInterruption:
時,會再次將-prepareToPlay
發送到音頻播放器實例。 如果您在中斷后沒有調用它,那么您的音頻會話可能不會重新啟動,這將產生您上面描述的效果 - 神秘的死音頻。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.