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];
Related
Hi I am trying to play live streaming api in my app but their is some error occurs like below...
Response Fail. Error : The operation couldn’t be completed. (Cocoa
error 3840.)
please help to sort out this problem
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",arrayId);
Service *srv=[[Service alloc]init];
NSString *str=#"http://streamtvbox.com/site/api/matrix/";
NSString *method=#"channel";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:arrayId forKey:#"id"];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
if (success) {
NSLog(#"Hello I am success");
}
NSLog(#"%#",responseObj);
_player = [[MPMoviePlayerViewController alloc] initWithContentURL:responseObj];
[self presentMoviePlayerViewControllerAnimated:_player];
}];
}
AVPlayerItem is the best choice in this case as you have more control.
See the below code snippet. I have given you just basic example. You do some re-search on AVPlayerItem.
Define your AVPlayer object:
AVPlayer *videoPlayer;
Prepare AVPlayer and add Observers:
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:imageText]];
videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[videoPlayer currentItem]];
[videoPlayer addObserver:self forKeyPath:#"status" options:0 context:nil];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(updateProgress:) userInfo:nil repeats:YES];
Handling callbacks:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == videoPlayer && [keyPath isEqualToString:#"status"])
{
if (videoPlayer.status == AVPlayerStatusFailed)
{
NSLog(#"AVPlayer Failed");
}
else if (videoPlayer.status == AVPlayerStatusReadyToPlay)
{
NSLog(#"AVPlayerStatusReadyToPlay");
[videoPlayer play];
}
else if (videoPlayer.status == AVPlayerItemStatusUnknown)
{
NSLog(#"AVPlayer Unknown");
}
}
if (object == videoPlayer && [keyPath isEqualToString:#"playbackLikelyToKeepUp"])
{
if (videoPlayer.playbackLikelyToKeepUp)
{
// Hide Activity indicator
[videoPlayer play];
}
}
if (object == videoPlayer && [keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (videoPlayer.playbackBufferEmpty)
{
// Show Activity indicator
[videoPlayer pause];
}
}
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
// code here whatever you want to do on finishing video stream..
}
Hi i created Avplayer for playing audio from server and its working perfectly but UISlider is not syncing with Audio even after updating UISlider method but the slider is moving properly but its not syncing with audio.i need to match that audio with UISlider
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;
[self.view addSubview:seekbar];
-(void)Audio{
NSString *urlString= #"https:/embed-ssl.wistia.com/deliveries/85dcf8de9db3830f47f136a4dba89114be58403f/dhwpxq4l9l.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];
NSLog(#"Audio playing");
}
- (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:(UISlider*)sender {
CGFloat currentSongTime = CMTimeGetSeconds([audioPlayer currentTime]);
seekbar.value = currentSongTime;
seekbar.minimumValue=0;
seekbar.maximumValue=currentSongTime;
}
- (void)updateProgress {
[seekbar setValue:CMTimeGetSeconds(audioPlayer.currentTime)];
}
Why are you changing the maximum value at every change?
You can set the minimumValue and maximumValue when you get AVPlayerStatusReadyToPlay according to audioPlayer.currentItem.duration
So instead of the seektime you can just use:
else if (audioPlayer.status == AVPlayerStatusReadyToPlay) {
NSLog(#"AVPlayerStatusReadyToPlay");
[audioPlayer play];
seekbar.minimumValue = 0;
seekbar.maximumValue = CMTimeGetSeconds(audioPlayer.currentItem.duration);
}
I have implemented AVPlayer. It is working fine. But many times during playing audio from URL, it stops/pauses automatically and takes very long time to resume/replay. On the other hand if I manually just pause and play it works fine means it does not take too much time to re-play. I want to resume/replay it whenever it is ready. Any suggestion will be great. Thank in advance !!!!!!!!
My code :
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (!songFinished) {
if (object == playerItem && [keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (playerItem.playbackBufferEmpty) {
printf("\n\n\t****player item playback buffer is empty****\n\n");
//[s activityIndicator] startAnimating];
[player pause];
}
}
else if (object == playerItem && [keyPath isEqualToString:#"playbackLikelyToKeepUp"])
{
if (playerItem.playbackLikelyToKeepUp)
{
printf("\n\n\t****Ready to Play audio ****\n\n");
[player play];
//Your code here
}
}
// for player status ------------------------------------------------------
else if (object == player && [keyPath isEqualToString:#"status"])
{
if (player.status == AVPlayerStatusFailed)
{
printf("\n\n\tAVPlayer Failed\n\n");
[ViewUtilities showAlert:AUDIO_PLAYER :AUDIO_PLAYER_FAILED_MESSAGE];
}
else if (player.status == AVPlayerStatusReadyToPlay)
{
printf("\n\n\tAVPlayerStatusReadyToPlay\n\n");
[player play];
nsTimer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTime:) userInfo:nil repeats:YES];
}
else if (player.status == AVPlayerItemStatusUnknown)
{
[ViewUtilities showAlert:AUDIO_PLAYER :AUDIO_PLAYER_UNKNOWN];
printf("\n\n\tAVPlayer Unknown\n\n");
}
if (!player)
{
return;
}
}
}
}
My app plays a streaming video, but when it buffers, the player goes to the pause mode and I have to set it to play mode again manually, I have the following code in my AVPlayer class in order to handle this situation, but it does not work.
In the ViewDidLoad method
[playerItem addObserver:self forKeyPath:#"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
[playerItem addObserver:self forKeyPath:#"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
and then, handling the observers using the following methods
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (!player)
{
return;
}
else if (object == playerItem && [keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (playerItem.playbackBufferEmpty) {
//Your code here
}
}
else if (object == playerItem && [keyPath isEqualToString:#"playbackLikelyToKeepUp"])
{
if (playerItem.playbackLikelyToKeepUp)
{
//Your code here
}
}
}
is there a another solution for this problem in order to get the player to continues play mode?
This might help,
suppose this is your AVPlayer object
player1 = [AVPlayer playerWithURL:streamURL];
When your video goes in buffer mode then you can pause it and when it done play it again like:
In observer method,
if ([object isKindOfClass:[AVPlayerItem class]])
{
AVPlayerItem *item = (AVPlayerItem *)object;
//playerItem status value changed?
if ([keyPath isEqualToString:#"status"])
{ //yes->check it...
NSLog(#"STATUS = %d",item.status);
switch(item.status)
{
case AVPlayerItemStatusFailed:
NSLog(#"player item status failed");
break;
case AVPlayerItemStatusReadyToPlay:
[playButton setTitle:#"Pause" forState:UIControlStateNormal];
[player1 play];
NSLog(#"player item status is ready to play");
break;
case AVPlayerItemStatusUnknown:
NSLog(#"player item status is unknown");
break;
}
}
else if ([keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (item.playbackBufferEmpty)
{
[playButton setTitle:#"Play" forState:UIControlStateNormal];
[player1 pause];
NSLog(#"player item playback buffer is empty");
}
}
}
or you can maintain on button click event.
Place one button on your screen to maintain play and pause and addTarget to it with OnClick event.
I've been trying to register my AVQueuePlayer items for KVO at the time of initializing. Below, the items in itemArray have all been properly created with URLs. After the code the queueList is added to a AVQueuePlayer. The player plays fine, with each item playing in order, but only observers for the first item trigger the response. The AVPlayerItemDidPlayToEnd works for all items, however.
I'm fairly new to KVO. Any help would be appreciated.
for(AVPlayerItem *i in itemArray)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(nextSong)
name:AVPlayerItemDidPlayToEndTimeNotification object:i];
[i addObserver:self forKeyPath:#"status" options:0 context:nil];
[i addObserver:self forKeyPath:#"playbackBufferEmpty" options:0 context:nil];
[i addObserver:self forKeyPath:#"playbackLikelyToKeepUp" options:0 context:nil];
[queueList addObject:item];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
AVPlayerItem *thisItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:#"rate"]) {
if ([self.player rate]!=0) {
[self setPlayButtonAsPlaying:YES];
NSLog(#"PLAYING");
}
else {
[self setPlayButtonAsPlaying:NO];
NSLog(#"PAUSED");
}
}
else if ([keyPath isEqualToString:#"status"])
{
if(thisItem.status==AVPlayerItemStatusFailed)
{
NSLog(#"failed");
[self setPlayButtonAsPlaying:NO];
[player pause];
}
}
else if ([keyPath isEqualToString:#"playbackBufferEmpty"])
{
if(thisItem.playbackBufferEmpty)
{
[player pause];
[self setPlayButtonAsPlaying:NO];
}
}
else if ([keyPath isEqualToString:#"playbackLikelyToKeepUp"])
{
if(!thisItem.playbackLikelyToKeepUp)
{
[player pause];
[self setPlayButtonAsPlaying:NO];
}
else
{
[player play];
[self setPlayButtonAsPlaying:YES];
}
}
}
EDIT: I also have a button which triggers this command, which I use to test the state of these properties.
NSLog(player.currentItem.playbackBufferEmpty ? #"Yes" : #"No");
NSLog(player.currentItem.playbackLikelyToKeepUp ? #"Yes" : #"No");
Specifically, playbackLikelyToKeepUp is false (which I manually cause by disconnecting my wifi). Interestingly, the playBackBufferEmpty is also false.