ios Knowing when a hls livestream has played the last chunk - ios

I do not have a problem a stream, but I do not know when it is buffering or when the stream has ended. Is there anyway to determine this in Objective-C. I have found solutions for audio and I even tried the AVPlayerItemDidPlayToEndTimeNotification but it does not work. Any suggestions?
NSString *url = liveStream.stream[#"cdn"];
dispatch_async(dispatch_get_main_queue(), ^{
AVPlayerItem *playerItem = [[AVPlayerItem alloc]
initWithURL:[NSURL URLWithString:url]];
[_player replaceCurrentItemWithPlayerItem:playerItem];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
[_player play];
});
}
-(void)itemDidFinishPlaying:(NSNotification *) notification {
}

In addition to the notification you're using, you should use KVO to observe the rate of the avPlayer, as well as the status of the avplayer's current AVPlayer item. From observing those properties, you can make a state machine of sorts where your player view controller knows what's going on, and can recover from various changes instate. There are various player states that you have to prepare for and recover from based on the properties that you observe.
Here's an answer on how to check for buffering
Here's an example of a complete AVPLayer
And of course, here's apple's documentation on AVPlayer
Here's the documentation on AVPlayerItem
Lastly, here's the link on KVOController. You'll thank me for this later.

Related

Playing videos from data obtained in chunks

I have recently started adding videos to ios apps using AVPlayer.But,now I have to get video data in chunks(HLS) rather than getting all data together ,but I am not able to understand the difference between this concept of playing data obtained in chunks or playing the whole data obtained altogether as implemented below .I have tried understanding this thing and looked for examples on internet but got the same thing as already implemented by me.Kindly give your suggestions and guidance that can help me to move forward.Thanks in advance!
-(void)playVideo:(NSURL*)videoURL
{
AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:videoURL];
AVPlayer* playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
_playerViewController = [[AVPlayerViewController alloc] init];
_playerViewController.player = playVideo;
_playerViewController.view.frame = self.view.bounds;
[self.view addSubview:_playerViewController.view];
[playVideo play];
}
Read this Document from Apple.
When you init player, it doesn't mean that player is ready to play. You should observe player's status until you get AVPlayerStatusReadyToPlay status.
From your code, you init player and directly start playing video. You should observe status of player by following code.
[player addObserver:self forKeyPath:#"status" options:0 context:&PlayerStatusContext];

MPMusicPlayerController breaks lock screen controls

I'm attempting to use MPMusicPlayerController to play apple music songs, but I can't get the lock screen controls to work. It seems as though MPMusicPlayerController overridess the remoteControlReceivedWithEvent listener.
Here is how I set up my controller:
self.player = [MPMusicPlayerController applicationMusicPlayer];
self.player.repeatMode = MPMusicRepeatModeNone;
self.player.shuffleMode = MPMusicShuffleModeOff;
[self.player beginGeneratingPlaybackNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handlePlaybackStateChanged:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:self.player ];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleItemChanged:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:self.player ];
Then I play apple music songs:
NSMutableArray *storeIDS = [NSMutableArray arrayWithObjects:anthem.song.apple_id, #"1", nil];
[self.player setQueueWithStoreIDs:storeIDS];
[self.player play];
[self.player setCurrentPlaybackRate:1.0];
For reference, here is how I setup the remote control listener in didFinishLaunchingWithOptions:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
At this point, the player plays the song as requested, but I can no longer receive any remote control notifications. Hitting next/prev simply stop the song since it has reached the end of the list. I've tried with the applicationMusicPlayer as well as the systemMusicPlayer. I can't use AVPlayer or AVAudioPlayer because it's Apple Music and I cannot get the URL to stream.
Any ideas!?
To play from Apple Music use MPMusicPlayerController.systemMusicPlayer()

Looping video in iOS cause a small pause/flash (MPMoviePlayerController & AVPlayer)

I'm really going crazy with my welcome view controller.
I have a video in background in continuos loop but every solution that I used causes a small pause/flash when the video is finished and loop.
I use two solution: MPMoviePlayerController and AVPlayer from AVFoundation but I got the same result, a small white flash when video is looped for replay.
My MPMoviePlayerController solution (I prefer a fix for this)
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *videoURL = [[NSBundle mainBundle] URLForResource:#"welcome_video" withExtension:#"mp4"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
self.moviePlayer.controlStyle = MPMovieControlStyleNone;
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
self.moviePlayer.view.frame = self.view.frame;
[self.view insertSubview:self.moviePlayer.view atIndex:0];
[self.moviePlayer prepareToPlay];
// Loop video
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(loopVideo) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
}
- (void)loopVideo
{
[self.moviePlayer play];
}
My AVPlayer solution
(void)viewDidLoad
{
[super viewDidLoad];
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
//Set up player
NSURL *movieURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"welcome_video" ofType:#"mp4"]];
AVAsset *avAsset = [AVAsset assetWithURL:movieURL];
AVPlayerItem *avPlayerItem =[[AVPlayerItem alloc]initWithAsset:avAsset];
self.avplayer = [[AVPlayer alloc]initWithPlayerItem:avPlayerItem];
AVPlayerLayer *avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:self.avplayer];
[avPlayerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[avPlayerLayer setFrame:[[UIScreen mainScreen] bounds]];
[self.movieView.layer addSublayer:avPlayerLayer];
//Config player
[self.avplayer seekToTime:kCMTimeZero];
[self.avplayer setVolume:0.0f];
[self.avplayer setActionAtItemEnd:AVPlayerActionAtItemEndNone];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.avplayer currentItem]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerStartPlaying)
name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.avplayer pause];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.avplayer play];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
- (void)playerItemDidReachEnd:(NSNotification *)notification
{
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}
- (void)playerStartPlaying
{
[self.avplayer play];
}
What's wrong with these implementation? I really try different fixes found on this site but nothing seems to work.
Any suggestions?
Hm.. I might have an idea for the AVPlayer-approach.
The AVPlayer has this method:
- (void)setRate:(float)rate
time:(CMTime)itemTime
atHostTime:(CMTime)hostClockTime
This means that you can specify WHEN you want the AVPlayer to start at kCMTimeZero. I have not actually used it, but I have an idea for how it can work.
You need to know exactly the moment you start the video the first time. I see you have your own -(void)playerStartPlaying which is called by the notificationCenter on didBecomeActive. I suggest using this method for app variations of [player play];, so put
[self playerStartPlaying];
inside viewDidAppear instead of [self.avplayer play];. It might be good enough.
If you here manage to find the device's hostClockTime, and add the length of the video, you should end up with the exact time when you want it to start from scratch. I am not testing any of this, and I'm typing from head, so you need to understand what I'm doing, and fix it yourself.
- (void)playerStartPlaying
{
//The device's hostClockTime. Basically a number indicating how long the device has been powered on.
CMTime hostClockTime = CMClockGetHostTimeClock;
//A CMTime indicating when you want the video to play the next time.
CMTime nextPlay = CMTimeAdd(hostClockTime, self.avplayer.currentItem.duration);
/* I don't know if that was correct or not, but you'll find out */
//Start playing if we're not already playing. There might be an avplayer.isPlaying or something, I don't know, this is probably working as well..
if(self.avplayer.rate != 1.0)
[self.avplayer play];
//Tell the player to restart the video at the correct time.
[self.avplayer setRate:1.0 time:kCMTimeZero atHostTime:nextPlay];
}
You'll have to remove the entire AVPlayerItemDidPlayToEndTimeNotification-thing. When the video has reached the end, it's already too late. What we're doing now is telling it when to play the second turn when we start the first. We want nothing to happen when didPlayToEndTime is fired, we're handling it manually.
So, if you understand what I have done above, you'll also notice that the video only will play twice. We tell the video to play, at the same time as we tell it to replay at time = now+videoLength. When that replay is done, nothing happens. It simply reaches end. To fix this, you'll need to somehow call -(void)playerStartPlaying at the same time as the setRate:time:atHostTime is executed on the AVPlayer. I guess you could start an NSTimer or dispatch_time and let it execute he method in exactly nextPlay-amount of time, but that would kinda defeat the purpose of this thing. Maybe not. You could try different stuff out. You probably CAN do this with some success, but I suggest finding a way to register for when the player started from the start. Maybe you can observe the rate or something, I don't know.. If you want to try it with a delayed method, you can try this:
double delayInSeconds = CMTimeGetSeconds(self.avplayer.currentItem.duration); //or something
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self playerStartPlaying];
});
Just keep in mind that this is some recursive shit, so even if you pause the video, this will still keep calling after that duration. In that case I suggest making a BOOL paused; and cancel the execution of the entire playerStartPlaying if it's set to YES. ..and of course set paused = YES; whenever you want to pause, next to wherever you say [player pause];
If this actually works, but you still get flashes, I know there are several ways to improve this. For instance, the CMTimeAdd() should probably be using some kind of synchronization-tool to make sure the times add up using the correct timeScale etc.
I have now spent way too much time writing this, and it might not even work. I have no idea. Good luck and good night.

How to call method/code when app is paused in iOS

As the title reads; I am currently playing a sound file on loop using this code:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"smoothjazz" ofType:#".mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:soundFilePath])
{
// Your code to play the sound file
[player setVolume:1.0];
player.numberOfLoops = 5; //infinite
[player play];
}
However, the music keeps playing when you pause the app (hit the home button). How can I call [player setVolume:0.0] when the app is paused and [player setVolume:1.0] when it is resumed?
All help appreciated.
You can use NSNotificationCenter to listen to the UIApplicationWillResignActiveNotification and UIApplicationDidBecomeActiveNotification notifications in your view controller (or whatever object your above code is in) and the pause/resume playing you sounds there.
You should probably not set the volume on your player. It would probably be better to call
[player pause] and [player play]
There is a protocol that handles state change: UIApplicationDelegate. The ones you are interested in right now are willResignActive and didBecomeActive.
Note that these are not didEnterBackground and willEnterForeground. The difference is the former will get hit when apps takeover, such as Siri, and the latter will not.
You can implement this protocol in your audio manager class and set the volume at that point, like so:
- (void)applicationWillResignActive:(UIApplication *)application {
self.currentVolume = self.player.volume;
self.player.volume = 0;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
self.player.volume = self.currentVolume;
}
There may be no need to store the current volume, but designing on it to be used like that now will allow you to implement that in the future.
You should consider whether or not you want to mute the player or pause it. I'm sure you have, but a general better practice here would be to pause it rather that mute it, but that's not something that applies to every situation.
Additionally, you should know that some programmers are of the school of thought that only the AppDelegate should implement the UIApplicationDelegate protocol. There's some good arguments for it, and personally, I'm not really decided on what's best practice on that, but if you want to follow that, then you can either set up a protocol to delegate these in your AppDelegate and have your audio manager implement that delegate or you can use NSNotificationCenter to broadcast the event to any listeners - so, your audio manager in this case. Of the two, I would say using notifications is a cleaner way to handle it (delegating to delegates is a bit silly to me), but they also can get messy if you're not careful.
Here's the code I added to the viewDidLoad to call the method on the app pausing:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(muteMusic)
name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(activateMusic)
name:UIApplicationDidBecomeActiveNotification object:nil];
Then, of course, my two methods:
- (void) muteMusic {
[player pause];
}
- (void) activateMusic {
[player play];
}
Enjoy!

iOS pause between songs to exec code then resume, when app is in background

I am building an app which needs to play a track list, but between each song the music should pause to execute some code, then once complete the music should resume. This needs to work when the app is in the background as well as in the foreground.
I have tried a couple of methods but none seem to be able to do everything I want.
AVQueuePlayer - I can't seem to identify when any one song has stopped, only when the whole queue has stopped.
AVPlayer - I can identify when the track has ended with a notification, then I can run my extra code then load the next track. This works fine as long as the app is not in the background, when the app is in the background the code executes fine except the [avPlayer play] command does not work. It does not throw an error, it simply does not play. I know it has moved to the next song and loaded it into AVPlayer as I output the meta data and it has moved on.
Just to be clear the initial track does run in the background, it is only starting the next track which does not run in the background.
Code below...
Any idea what I am doing wrong?
Thanks!
+(void) playItem {
//get the play item from the song array based on intSongIndex
MPMediaItem *currentSong = [songsNowPlaying objectAtIndex:intSongIndex];
AVPlayerItem * currentItem = [AVPlayerItem playerItemWithURL:[currentSong valueForProperty:MPMediaItemPropertyAssetURL]];
[avPlayer replaceCurrentItemWithPlayerItem:currentItem];
//add notification to the currentItem
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:currentItem];
//play
[avPlayer play];
NSArray *metadataList = [[avPlayer currentItem].asset commonMetadata];
for (AVMetadataItem *metaItem in metadataList) {
NSLog(#"%#: %#",[metaItem commonKey], [metaItem value]);
}
//increment song index so next time the next song is selected
intSongIndex ++;
if (intSongIndex >= songsNowPlaying.count) {
intSongIndex = 0;
}
}
+ (void)playerItemDidReachEnd:(NSNotification *)notification {
//add code to be executed before the next song plays
//call playItem to play the next song
[self playItem];
}
Solved, this needed adding to the initial viewDidLoad
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

Resources