AVPlayer无法在自定义类中工作

时间:2013-04-02 09:56:58

标签: ios objective-c avplayer

我不知道我哪里出错了。 [audioPlayer播放],[audioPlayer停止]无法正常工作。因为audioPlayer是零。但是,如果我尝试在状态检查AVPlayerStatusReadyToPlay中播放audioPlayer,那么它工作正常,但仍然其他按钮不起作用相同audioPlayer nil。

customClass.h

@property (nonatomic, retain) AVPlayer *audioPlayer;

customClass.m

-(void)prepareAudioPlayerFor:


    NSURL *urlPath = [NSURL URLWithString:@"http://freshmp3music.ru/music/04.2013/chris_brown_-_fine_china_(www.freshmp3music.ru).mp3"];

   AVAsset *asset = [AVURLAsset URLAssetWithURL:urlPath options:nil];
   AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];

   AVPlayer *player = [AVPlayer playerWithPlayerItem:anItem];

    audioPlayer = player;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[audioPlayer currentItem]];

    [audioPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == audioPlayer && [keyPath isEqualToString:@"status"]) {
        if (audioPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");

        } else if (audioPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            if(audioPlayer.currentItem == nil)
            {
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"No Audio Anthem Found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];

            }else
            {

                NSLog(@"readyToPlay");
              //  [audioPlayer play];  // Here Play works fine but still other buttons not work
            }

        } else if (audioPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");

        }
    }
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
    NSLog(@"finished");

   // [self playPauseBtn:nil];
    CMTime fiveSecondsIn = CMTimeMake(0, 1);
    [audioPlayer seekToTime:fiveSecondsIn];
    [audioPlayer pause];
}

- (IBAction)playBtn:(id)sender {
    if (audioPlayer == nil) {
        NSLog(@"Player Nil");
    }
    [audioPlayer play]; // this don't work why

}

OUTPUT : AVPlayerStatusReadyToPlay
OUTPUT : readyToPlay
OUTPUT : Player Nil

0 个答案:

没有答案