2011-12-07 6 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]; 
} 

에 내 코드를 가지고 있지만 UIApplicationMain

에 오류 Program received signal: "SIGABRT" 받고 있어요? 이것이 내가 어떻게해야하는지, 어디에서 문제를 점검하기 시작할 것인가?

답변

8

예 App Delegate에서 AVAudioPlayer를 사용할 수 있습니다.

당신이해야 할 것은 : - appDelegate.h 파일에서 는 수행 -

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

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

backgroundMusicPlayer 속성을 확인하고 sythesize.

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

나는 당신의 정확한 구현을 사용하지 않았다 이러한 줄을 추가,하지만 난 뽑아 -이 : 파일 appDelegate.m에서

가 할 내가 필요한 조각들을 꺼내. 감사! – Jacksonkr

관련 문제