Find out whether AVPlayer is loading or playing mp3 from internet - ios

I would like to use AVPlayer to stream a .mp3 from internet
[[AVPlayer alloc] initWithURL:url];
It all works apart from the fact that I am unable to tell whether player is Loading (buffering) or playing ?
I have tried to use KVO on many properties, but none seem to provide me with a simple way of determining whether the AVPlayer is currently actually playing audio or whether it is loading data. It is driving me nuts.
Thank you for your suggestions in advance

You can detect when buffering is done and playback has started by creating a periodic time observation (using addPeriodicTimeObserverForInterval:queue:usingBlock:) to detect when the play time has started to move. For example:
AVPlayer *player;
// allocate AVPlayer and start playing
__weak PlayerController *blockSelf = self;
id observerToken = [player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC)
queue:nil
usingBlock:^ (CMTime time)
{
if (CMTimeGetSeconds(time) > 0.0)
{
// done buffering, should be playing now
[player removeTimeObserver:[blockSelf playerTimeObserverToken]];
[blockSelf setPlayerTimeObserverToken:observerToken:nil];
}
}];
[self setPlayerTimeObserverToken:observerToken]; // Keep a reference to the token for later use in block.

Related

AVPlayer seekToTime -- finished is NO -- Can't get player to play again

I'm using the AVPlayer method:
- (void)seekToTime:(CMTime)time
toleranceBefore:(CMTime)toleranceBefore
toleranceAfter:(CMTime)toleranceAfter
completionHandler:(void (^)(BOOL finished))completionHandler
for scrubbing a video. toleranceBefore and toleranceAfter are both 0.
However, when the user scrubs to within about 5 seconds of the end, on certain videos, finished is always equal to NO.
The player will then be in an inconsistent state where pause and play methods do nothing. The video is frozen at the time passed to seekToTime.
This happens consistently on some videos, and not at all on others.
I have a simple if/else but I don't know what to put in the else to get the player to play again:
[_avPlayer seekToTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC)
toleranceBefore:toleranceBefore
toleranceAfter:toleranceAfter
completionHandler:^(BOOL finished) {
if(finished){
}
else {
// How to get the player to play again??
}
}];
Like I said above, I've tried putting _avPlayer play in there but it doesn't play.

How do I control playback of a video in an iOS Sprite Kit SKVideoNode?

I load a video into my Sprite Kit SKVideoNode, but how do I stop and restart the playback or go to a specific time in the video? All I see are play and pause methods.
// AVPlayer
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"HowToPlay" ofType:#"mp4"]];
_avPlayer = [AVPlayer playerWithURL:fileURL];
// SKVideoNode
_videoNode = [SKVideoNode videoNodeWithAVPlayer:_avPlayer];
[_videoNode play];
This turned out to work for me.
Restart:
[_videoNode removeFromParent];
_videoNode = [SKVideoNode videoNodeWithVideoFileNamed:#"video.mp4"];
_videoNode.position = ...
_videoNode.size = ...
[self addChild:_videoNode];
[_videoNode play];
Pause:
[_videoNode pause];
_videoNode.paused = YES;
Play:
[_videoNode play];
_videoNode.paused = NO;
All you can do with a SKVideoNode is documented here. play and pause are the only supported playback methods.
There is no stop because its equivalent to pause in this context - what should "stop" do, render a black texture? If the SKVideoNode should be removed on "stop" then just send it the removeFromParent message, that'll "stop" it.
Rewind is unnecessary because you can simply run the play method again or create a new SKVideoNode.
I assume jumping to a specific timeframe isn't supported because this can't be instant, so again there's the problem of what the node should display in the time until the video playback position was moved to the specified timestamp?
If you keep a reference to the AVPlayer object used to initialize the video node then you can control playback with its methods

How do I configure AVPlayer to play a video that was recorded at 120fps?

I have a simple app that records video at 120fps, saves it to the documents directory, and then uses an instance of AVPlayer to play it back.
If I set the playback rate to 1.0 (for the AVPlayer instance), the playback is a bit choppy (probably more along the lines of 60fps). However, if I interrupt the playback by pressing the "play" button (which then sets the playback rate to 1.0 again!), it plays back very smoothly.
For instance, this is what occurs when the user presses the play button (and yes, I observe the 'status' property of AVPlayer before allowing the user to play the video):
- (IBAction)playButtonPressed:(id)sender
{
[self.videoPlayer seekToTime:kCMTimeZero];
[self.videoPlayer setRate:1];
self.videoPlayer.volume = 1;
}
And this is my simple player-setup code:
- (void)setUpAVPlayer
{
self.videoURL = [[NSURL alloc] initFileURLWithPath:self.videoURL.path];
self.videoPlayer = [AVPlayer playerWithURL:self.videoURL];
[self.previewLayer setPlayer:self.videoPlayer];
// observe player status
[self.videoPlayer addObserver:self
forKeyPath:#"status"
options:0
context:nil];
}
There really is nothing unusual about what I'm doing. It plays back video fine. It's only the case where the video was recorded at 120fps that there is a playback issue.
(Also, this is running on my iPhone5s since it is the only device that supports 120fps.)

MPMoviePlayerController fail to play audio

I use MPMoviePlayerController to play a list of audio streams from url. I use the following code to init the player
self.player = [[[MPMoviePlayerController alloc] init] autorelease];
self.player.controlStyle = MPMovieControlStyleNone;
and later use the following code to set and reset contentUrl:
self.player.contentURL = url;
[self.player prepareToPlay];
but sometimes, not every time, it fails to play audio, post MPMoviePlayerPlaybackDidFinishNotification directly and gives following userInfo
{
MPMoviePlayerPlaybackDidFinishReasonUserInfoKey = 1;
error = "Error Domain=MediaPlayerErrorDomain Code=-11828 \"Cannot Open\" UserInfo=0xee7bf20 {NSLocalizedDescription=Cannot Open}";
}
anyone knows why?
I would suggest you use AVPlayer instead of MPMoviePlayerController.
I had seen such issues before when streaming audio with MPMoviePlayerController. AVPlayer is the more appropriate one for this task.

How to mute/unmute audio when playing video using MPMoviePlayerController?

I've created my own custom controls for use with the MPMoviePlayerController. So far everything works except the mute button control.
I've configured the AVAudioSession using the following code before I create my instance of the MPMoviePlayerController.
NSError *modeError = nil;
[self.audioSession setMode:AVAudioSessionModeMoviePlayback error:&modeError];
if (modeError != nil) {
NSLog(#"Error setting mode for AVAudioSession: %#", modeError);
}
NSError *categoryError = nil;
[self.audioSession setCategory:AVAudioSessionCategoryPlayback error:&categoryError];
if (categoryError != nil) {
NSLog(#"Error setting category for AVAudioSession: %#", categoryError);
}
Then in my mute button callback method I have the following code:
NSError *activeError = nil;
[self.audioSession setActive:NO error:&activeError];
if (activeError != nil) {
NSLog(#"Error setting inactive state for AVAudioSession: %#", activeError);
}
When clicking the Mute button I get the following unuseful error:
Error Domain=NSOSStatusErrorDomain Code=560030580 "The operation couldn’t be completed. (OSStatus error 560030580.)"
I am linking to the AVFoundation framework.
This is really starting to bug me as I can't for the life of me work out a way to reduce or mute the playback audio of my application.
I don't want to change the system global volume just the application level volume as defined by the AVAudioSession AVAudioSessionCategoryPlayback category.
It seems that you can set the volume of the AVAudioPlayer but not the MPMoviePlayerController. I've seen other posts here on SO that say just create an instance of AVAudioPlayer and set the volume but this just causes my app to crash and I expect it has something to do with the fact I'm not using the initWithContentsOfURL:error: or initWithData:error: and instead using `init'.
Any help would be appreciated.
After speaking to an Apple technician it turns out that it's not possible to control or mute the audio using MPMoviePlayerController.
Instead you have to create your own controller using AVFoundations AVPlayer class.
Once you're using that it's a matter of creating a custom audio mix and setting the volume level. It actually works very well.
Sample code:
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:[self localMovieURL] options:nil];
NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
// Mute all the audio tracks
NSMutableArray * allAudioParams = [NSMutableArray array];
for (AVAssetTrack *track in audioTracks) {
AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
[audioInputParams setVolume:0.0 atTime:kCMTimeZero ];
[audioInputParams setTrackID:[track trackID]];
[allAudioParams addObject:audioInputParams];
}
AVMutableAudioMix * audioZeroMix = [AVMutableAudioMix audioMix];
[audioZeroMix setInputParameters:allAudioParams];
// Create a player item
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem setAudioMix:audioZeroMix]; // Mute the player item
// Create a new Player, and set the player to use the player item
// with the muted audio mix
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
self.mPlayer = player;
[mPlayer play];
I've written an MPMoviePlayerController replacement class that adds support for volume level. I will upload the to github shortly and add the link in this post.
I know this is an old post, but I managed to find a way to successfully control the volume of the MPMoviePlayerController control in iOS6 & iOS7, using an MPVolumeView. One gotcha is that it does NOT work in the simulator, only on the physical device. For just controlling the volume, adding a hidden MPVolumeView will work fine. However if you use a hidden one, the native OS volume display that appears when you change the volume using the physical device volume buttons will still appear centre screen. If you want to prevent this, make sure your MPVolumeView is not hidden. Instead, you can give it a very low alpha transparency and place it behind other views, so the user can't see it.
Here's the code i've used:
MPVolumeView *volumeView = [[MPVolumeView alloc]initWithFrame:CGRectZero];
[volumeView setShowsVolumeSlider:YES];
[volumeView setShowsRouteButton:NO];
// control must be VISIBLE if you want to prevent default OS volume display
// from appearing when you change the volume level
[volumeView setHidden:NO];
volumeView.alpha = 0.1f;
volumeView.userInteractionEnabled = NO;
// to hide from view just insert behind all other views
[self.view insertSubview:volumeView atIndex:0];
This allows you to control the volume by calling:
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];
But I was still getting the native OS volume display appearing the first time I would try to change the volume - on subsequent loads it did not show this display, so figuring it was something to do with the stage in the viewcontroller life cycle, I moved it from my viewDidLoad method to the viewDidAppear method - it worked - the volume muted and the native volume display did not appear, but I now was able to hear a split second of audio before the video started playing. So I hooked into the playback state did change delegate of the MPMoviePlayerController. In viewDidload I added:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(videoPlaybackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
And the delegate callback method:
-(void)videoPlaybackStateDidChange:(NSNotification *)aNotification
{
// Note, this doesn't work in simulator (even in iOS7), only on actual device!
if ([moviePlayerController playbackState] == MPMoviePlaybackStatePlaying)
{
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];
}
}
This muted the audio of the video before it started playing, but after the viewDidLoad in the life cycle, so no native OS volume muted display.
In my app, I retrieved and stored the current volume level before muting (using [MPMusicPlayerController applicationMusicPlayer].volume property), and then restored the volume to this level when the view controller was closed, meaning the user would be unaware that their device volume level was modified and reverted.
Also, if your MPMoviePlayerController is using a non-standard audio route in iOS7, calling [[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0] may not work for you - in this case you can loop through the subviews of your MPVolumeView control until you find a view which subclasses UISlider. You can then call [sliderView setValue:0 animated:NO] which should work for you. This method isn't using any private Apple APIs so shouldn't get your app rejected - after all there are so many legitimate reasons why you would offer this functionality, and it was possible in iOS6 without having to go to these lengths! In fact, I was bamboozled to discover that Apple had removed the functionality to set the volume on MPMoviePlayerController in iOS7 in the first place.. enforced migration to AVPlayer?
Update: My iPad app has now been approved using this method and is live on the app store.

Resources