2011-12-07 9 views
3

私はTabBarControllerに2つのタブがあり、両方のタブで音楽を再生したいと思います。今、私はメイン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

関連する問題