我可以在AppDelegate上使用AVAudioPlayer吗?

我有一个TabBarController与两个选项卡,我想在两个选项卡上播放音乐。 现在我有我的代码在主appDelegate

 NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"My Song" ofType:@"m4a"]]; // My Song.m4a NSError *error; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; if (error) { NSLog(@"Error in audioPlayer: %@", [error localizedDescription]); } else { //audioPlayer.delegate = self; [audioPlayer prepareToPlay]; } 

但我得到错误Program received signal: "SIGABRT" UIApplicationMain上的Program received signal: "SIGABRT"

有没有更好的方法来完成我想要做的事情? 如果这是我应该怎么做的,我该从哪里开始检查问题?

是的,你可以在App Delegate中使用AVAudioPlayer。

你需要做的是: – 在appDelegate.h文件做: –

 #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> AVAudioPlayer *_backgroundMusicPlayer; BOOL _backgroundMusicPlaying; BOOL _backgroundMusicInterrupted; UInt32 _otherMusicIsPlaying; 

设置backgroundMusicPlayer属性并进行合并。

appDelegate.m文件中: –

在FinishLaunching方法中添加这些行

 NSError *setCategoryError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError]; // Create audio player with background music NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"SplashScreen" ofType:@"wav"]; NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath]; NSError *error; _backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error]; [_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions [_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever 

现在实现委托方法

 #pragma mark - #pragma mark AVAudioPlayer delegate methods - (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player { _backgroundMusicInterrupted = YES; _backgroundMusicPlaying = NO; } - (void) audioPlayerEndInterruption: (AVAudioPlayer *) player { if (_backgroundMusicInterrupted) { [self tryPlayMusic]; _backgroundMusicInterrupted = NO; } } - (void)tryPlayMusic { // Check to see if iPod music is already playing UInt32 propertySize = sizeof(_otherMusicIsPlaying); AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &_otherMusicIsPlaying); // Play the music if no other music is playing and we aren't playing already if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) { [_backgroundMusicPlayer prepareToPlay]; if (soundsEnabled==YES) { [_backgroundMusicPlayer play]; _backgroundMusicPlaying = YES; } } }