2011-12-07 76 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

相關問題