2012-03-05 4 views
0

나는이 문제를 해결하기 위해 며칠 째 고생하고 있으며 단지 길을 찾을 수 없습니다. 앱을 종료 할 때 또는 Safari로 이동하기 위해 링크를 클릭 할 때 백그라운드에서 오디오를 재생하고 싶지만 백그라운드 모드로 이동하지는 않습니다. 도와주세요.백그라운드 오디오가 재생되지 않음

FirstViewController.h 파일 :

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

@interface RygestopFirstViewController : UIViewController <AVAudioPlayerDelegate> { 

    IBOutlet UIButton     *playButton; 
    IBOutlet UISlider     *volumeSlider; 
    IBOutlet UISlider     *progressBar; 
    IBOutlet UILabel     *currentTime; 
    IBOutlet UILabel     *duration; 

    AVAudioPlayer      *player; 
    UIImage        *playBtnBG; 
    UIImage        *pauseBtnBG; 
    NSTimer        *updateTimer; 

    BOOL        inBackground; 

} 

- (IBAction)playButtonPressed:(UIButton*)sender; 
- (IBAction)volumeSliderMoved:(UISlider*)sender; 
- (IBAction)progressSliderMoved:(UISlider*)sender; 

@property (nonatomic, retain) UIButton  *playButton; 
@property (nonatomic, retain) UISlider  *volumeSlider; 
@property (nonatomic, retain) UISlider  *progressBar; 
@property (nonatomic, retain) UILabel   *currentTime; 
@property (nonatomic, retain) UILabel   *duration; 

@property (nonatomic, retain) NSTimer   *updateTimer; 
@property (nonatomic, assign) AVAudioPlayer   *player; 

@property (nonatomic, assign) BOOL   inBackground; 

@end 

FirstViewController.m 코드 :

// amount to skip on rewind or fast forward 
#define SKIP_TIME 1.0   
// amount to play between skips 
#define SKIP_INTERVAL .2 

@implementation RygestopFirstViewController 

@synthesize playButton; 
@synthesize volumeSlider; 
@synthesize progressBar; 
@synthesize currentTime; 
@synthesize duration; 
@synthesize updateTimer; 
@synthesize player; 
@synthesize inBackground; 

-(void)updateCurrentTimeForPlayer:(AVAudioPlayer *)p 
{ 
    currentTime.text = [NSString stringWithFormat:@"%d:%02d", (int)p.currentTime/60, (int)p.currentTime % 60, nil]; 
    progressBar.value = p.currentTime; 
} 

- (void)updateCurrentTime 
{ 
    [self updateCurrentTimeForPlayer:self.player]; 
} 

- (void)updateViewForPlayerState:(AVAudioPlayer *)p 
{ 
    [self updateCurrentTimeForPlayer:p]; 

    if (updateTimer) 
     [updateTimer invalidate]; 

    if (p.playing) 
    { 
     [playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal]; 

     updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateCurrentTime) userInfo:p repeats:YES]; 
    } 
    else 
    { 
     [playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal]; 
     updateTimer = nil; 
    } 

} 

- (void)updateViewForPlayerStateInBackground:(AVAudioPlayer *)p 
{ 
    [self updateCurrentTimeForPlayer:p]; 

    if (p.playing) 
    { 
     [playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal]; 
    } 
    else 
    { 
     [playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal]; 
    } 
} 

-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p 
{ 
    duration.text = [NSString stringWithFormat:@"%d:%02d", (int)p.duration/60, (int)p.duration % 60, nil]; 
    progressBar.maximumValue = p.duration; 
    volumeSlider.value = p.volume; 
} 

-(void)pausePlaybackForPlayer:(AVAudioPlayer*)p 
{ 
    [p pause]; 
    [self updateViewForPlayerState:p]; 
} 

-(void)startPlaybackForPlayer:(AVAudioPlayer*)p 
{ 
    if ([p play]) 
    { 
     [self updateViewForPlayerState:p]; 
    } 
    else 
     NSLog(@"Could not play %@\n", p.url); 
} 

- (IBAction)playButtonPressed:(UIButton *)sender 
{ 
    if (player.playing == YES) 
     [self pausePlaybackForPlayer: player]; 
    else 
     [self startPlaybackForPlayer: player]; 
} 

- (IBAction)volumeSliderMoved:(UISlider *)sender 
{ 
    player.volume = [sender value]; 
} 

- (IBAction)progressSliderMoved:(UISlider *)sender 
{ 
    player.currentTime = sender.value; 
    [self updateCurrentTimeForPlayer:player]; 
} 

- (void)dealloc 
{ 
    [super dealloc]; 

    [playButton release]; 
    [volumeSlider release]; 
    [progressBar release]; 
    [currentTime release]; 
    [duration release]; 

    [updateTimer release]; 
    [player release]; 

    [playBtnBG release]; 
    [pauseBtnBG release]; 
} 

#pragma mark AVAudioPlayer delegate methods 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag 
{ 
    if (flag == NO) 
     NSLog(@"Playback finished unsuccessfully"); 

    [p setCurrentTime:0.]; 
    if (inBackground) 
    { 
     [self updateViewForPlayerStateInBackground:p]; 
    } 
    else 
    { 
     [self updateViewForPlayerState:p]; 
    } 
} 

- (void)playerDecodeErrorDidOccur:(AVAudioPlayer *)p error:(NSError *)error 
{ 
    NSLog(@"ERROR IN DECODE: %@\n", error); 
} 

// we will only get these notifications if playback was interrupted 
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)p 
{ 
    NSLog(@"Interruption begin. Updating UI for new state"); 
    // the object has already been paused, we just need to update UI 
    if (inBackground) 
    { 
     [self updateViewForPlayerStateInBackground:p]; 
    } 
    else 
    { 
     [self updateViewForPlayerState:p]; 
    } 
} 

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)p 
{ 
    NSLog(@"Interruption ended. Resuming playback"); 
    [self startPlaybackForPlayer:p]; 
} 

#pragma mark background notifications 
- (void)registerForBackgroundNotifications 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(setInBackgroundFlag) 
               name:UIApplicationWillResignActiveNotification 
               object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(clearInBackgroundFlag) 
               name:UIApplicationWillEnterForegroundNotification 
               object:nil]; 
} 

- (void)setInBackgroundFlag 
{ 
    inBackground = true; 
} 

- (void)clearInBackgroundFlag 
{ 
    inBackground = false; 
} 



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.title = NSLocalizedString(@"Play", @"First"); 
     self.tabBarItem.image = [UIImage imageNamed:@"Home"]; 
    } 
    return self; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Release any cached data, images, etc that aren't in use. 
} 

//Make sure we can recieve remote control events 
- (BOOL)canBecomeFirstResponder { 
    return YES; 
} 

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    playBtnBG = [[UIImage imageNamed:@"Player.png"] retain]; 
    pauseBtnBG = [[UIImage imageNamed:@"Pause.png"] retain]; 

    [playButton setImage:playBtnBG forState:UIControlStateNormal]; 

    [self registerForBackgroundNotifications]; 

    updateTimer = nil; 

    duration.adjustsFontSizeToFitWidth = YES; 
    currentTime.adjustsFontSizeToFitWidth = YES; 
    progressBar.minimumValue = 0.0; 

    // Load the the sample file, use mono or stero sample 

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"Sound1" ofType:@"m4a"]]; 

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
    if (self.player) 
    { 
     [self updateViewForPlayerInfo:player]; 
     [self updateViewForPlayerState:player]; 
     player.numberOfLoops = 0; 
     player.delegate = self; 
    } 


    [fileURL release]; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

@end 

이 그리고, 그런데, 내가 탭 표시 줄 응용 프로그램에서 얇은 실행하려면, 그래서 백그라운드 모드가 있어야합니다 항상 선물한다.

+1

가능한 복제본 [AVPlayer를 사용한 오디오의 Airplay는 백그라운드에서 작동하지 않습니다.] (http://stackoverflow.com/questions/8807914/airplay-of-audio-using-avplayer-does-not-work-in- 배경) – bryanmac

+0

정보를위한 THx. 그러나이 코드를 어디에 넣어야합니까? Im 프로그래밍에 n00b, 그래서 제발 도와주세요. – Smugl3r

답변

관련 문제