2011-12-07 48 views
3

我有一个TabBarController两个选项卡,我想要在两个选项卡上播放音乐。现在我对主appDelegateIOS可以在appDelegate上使用AVAudioPlayer吗?

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

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

回答

8

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

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

#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 

AVAudioPlayer *_backgroundMusicPlayer; 
BOOL _backgroundMusicPlaying; 
BOOL _backgroundMusicInterrupted; 
UInt32 _otherMusicIsPlaying; 

backgroundMusicPlayer财产和sythesize它。

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; 


     } 
    } 
} 
+1

我没有使用完全实现,但是我拉我需要的东西。谢谢! – Jacksonkr

相关问题