简体   繁体   中英

Avplayer issues with UISlider

Hi i just created AVplayer for playing audio from server. My problem is my UISlider is not moving based on Audioplayer .please help me out to overcome this problem.

    seekbar =[[UISlider alloc]init];
    seekbar.frame=CGRectMake(10,CGRectGetMinY(PlayAudio.frame)-50, CGRectGetWidth(self.view.frame)-20, 20);
    [seekbar addTarget:self action:@selector(seekTime:) forControlEvents:UIControlEventValueChanged];
    seekbar.continuous=YES;
    seekbar.minimumValue=0;
    seekbar.maximumValue=20;
    [self.view addSubview:seekbar];

    -(void)Audio{
        NSString *urlString= @"https.wav";

        audioPlayer = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playerItemDidReachEnd:)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:[audioPlayer currentItem]];
        [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
        [audioPlayer play];


    }

    - (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");
                [audioPlayer play];


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

            }
        }
    }

    - (void)seekTime:(id)sender {

        [seekbar setValue:CMTimeGetSeconds(audioPlayer.currentTime)];
    }

seekTime is only called when the user moves the slider. So that is not a good place for updating it.

You should have a updateProgress method, that is called from the NSTimer, that's where you need to update the slider position:

- (void)updateProgress {
        [seekbar setValue:CMTimeGetSeconds(audioPlayer.currentTime)];
}

So everytime the NSTimer fires, it should update the position of the slider.

On the seekTime method you should do the opposite: set the audio playback to the point that the user selected. Something like this:

[audioPlayer setCurrentTime:seekbar.value];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM