iOS AVAudioPlayer Volume Control - ios

I've read quite a few posts on the subject but the answers are not 100% clear. I'm looking for clarity here.
My app plays a short AVAudioPlayer sound periodically. The problem is, I can only set the volume after the first sound is played.
After reading stackoverflow, everyone seems to suggest that I play a dummy (silent) AVAudioPlayer sound at the start of the app to "link" the device's volume buttons to the "app volume".
Said another way, when the app starts, it's the "Ringer" volume that is controlled by default and only after the first sound is played will the device's volume buttons finally control the "app volume" (AVAudioPlayer volume) (it's the image without any label). Unfortunately by the time this happens, the user doesn't hear the first sound and now sees the app as broken.
My question is, is this the answer? Do I simply play a short dummy sound once at the start of the app to "link" the device's volume buttons to the app?

You don't have to play a dummy sound. Using the AudioToolbox framework you can set the AudioSessionActive as follows:
AudioSessionInitialize (NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);
AudioSessionSetActive (true);
This will allow the volume buttons to control the app volume.
See this question: Cannot Control Volume of AVAudioPlayer via Hardware Buttons when AudioSessionActive is NO for more information on this approach.

Hey for future answer searchers, Since AudioSessionInitialize and AudioSessionSetActive are deprecated in iOS7 the recommended way of handling hardware audio and getting call backs is by using an AVAudioSession object. Set the session as active for your app and KVO on the #"outputVolume" property of the session.
- (id)init
{
self = [super init];
if (self)
{
self.audioSession = [AVAudioSession sharedInstance];
[_audioSession setActive:YES error:nil];
[_audioSession addObserver:self forKeyPath:#"outputVolume" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:NULL];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:#"outputVolume"])
{
[self setVolume:[change[#"new"] floatValue]];
}
}
- (void)dealloc
{
[_audioSession removeObserver:self forKeyPath:#"outputVolume"];
[_audioSession setActive:NO error:nil];
}

Related

iOS add audio playing via AVPlayer to OS default player?

So the idea is - when we play audio in Music app in iPhone and press home button then swipe from bottom of the screen, we can see the audio playing in default OS player with play/pause controls and audio continue play.
Now what i need to do, i play an audio by using AVAudioPlayer in my app and if user press home button, the audio need to play continue as in case of music app.
But i have no idea how to add audio in OS default player? Any help or suggestion would be highly appreciated.
Edit: I need to play audio using streaming so i guess i need to use AVPlayer instead of AVAudioPlayer
You could use an MPMovieplayerController since you'll be more than likely be using an M3U8 playlist.
Here's the documentation http://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/mpmovieplayercontroller_class/index.html
But it basically goes like this:
Initialize the MPMoviePlayerController, assign a file type (stream), put the source url, and present it in the view stack.
For the background audio, you'd have to use AudioSession like in this answer iOS MPMoviePlayerController playing audio in background
You can do this as a background audio task so that the audio keeps playing even after the user presses the home button and your app goes into the background. First you create an AVAudioSession. Then you set up an array of AVPlayerObjects and a AVQueuePlayer in your viewDidLoad method. There's a great tutorial by Ray Wenderlich that discusses all of this in detail http://www.raywenderlich.com/29948/backgrounding-for-ios. You can set up a callback method (observer method) so that the app is sent additional audio data as it streams in - (void)observeValueForKeyPath.
Here's how the code looks (from Ray Wenderlich's tutorial):
in viewDidLoad:
// Set AVAudioSession
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
// Change the default output audio route
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
NSArray *queue = #[
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:#"IronBacon" withExtension:#"mp3"]],
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:#"FeelinGood" withExtension:#"mp3"]],
[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:#"WhatYouWant" withExtension:#"mp3"]]];
self.player = [[AVQueuePlayer alloc] initWithItems:queue];
self.player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;
[self.player addObserver:self
forKeyPath:#"currentItem"
options:NSKeyValueObservingOptionNew
context:nil];
in a callback method:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:#"currentItem"])
{
AVPlayerItem *item = ((AVPlayer *)object).currentItem;
self.lblMusicName.text = ((AVURLAsset*)item.asset).URL.pathComponents.lastObject;
NSLog(#"New music name: %#", self.lblMusicName.text);
}
}
Don't forget to add the member variables in your view controller's private API in the implementation file:
#interface TBFirstViewController ()
#property (nonatomic, strong) AVQueuePlayer *player;
#property (nonatomic, strong) id timeObserver;
#end

AVQueuePlayer not advancing to next item in iOS 8

I am using AVQueuePlayer to play a few videos, everything works fine in iOS 6 & 7. However, in iOS 8, when the current AVPlayerItem finishes playing the next video does not play. Placing an observer on the queue's currentItem property shows the the queue has the next video set as its current item as expected, it just does not play (even with explicit play calls).
Does anyone have any insight into what might be happening and how to fix it? Has anyone else come across this issue?
I had exactly the same issue and I wasted ten hours on this...
But it fixed now by adding the "insertItem" method into the main thread.
So I have my player as a property :
#property AVQueuePlayer * player;
I just init it like this :
_player = [[AVQueuePlayer alloc] init];
And here is my method to add items from a path :
- (void)addInQueuePlayerFile:(NSString *)path {
AVAsset * asset = [AVAsset assetWithURL:[[NSURL alloc] initFileURLWithPath:path]];
AVPlayerItem * playerItem = [AVPlayerItem playerItemWithAsset:asset];
dispatch_async(dispatch_get_main_queue(), ^{
[_player insertItem:playerItem afterItem:nil];
});
}
So its working but I don't really understand why... So if someone has an answer...
But also if this doesn't work for you, try to add an observer to your player (and/or your playerItem). You can add an observer like that :
[_player addObserver:self forKeyPath:#"status" options:0 context:nil]
And catch it with this method :
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == _player && [keyPath isEqualToString:#"status"]) {
if (_player.status == AVPlayerStatusFailed) {
NSLog(#"AVPlayer Failed");
} else if (_player.status == AVPlayerStatusReadyToPlay) {
NSLog(#"AVPlayer item Ready to Play");
} else if (_player.status == AVPlayerStatusUnknown) {
NSLog(#"AVPlayer item Unknown");
}
}
}
Let me know if this work for you.
The avplayer should always be accessed on the main thread. This is nothing new to iOS8 but perhaps Apple changed how threads are used so you're seeing the issue more often than in iOS7.
To ensure safe access to a player’s nonatomic properties while dynamic changes in playback state may be reported, you must serialize access with the receiver’s notification queue. In the common case, such serialization is naturally achieved by invoking AVPlayer’s various methods on the main thread or queue.
https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVPlayer_Class/index.html
I had the same problem. After several hours of trial, I found that if some of the items in queue have different encryption methods, the player would stall.
For example, if the player just finished playing an encrypted stream, and the next item in queue was unencrypted, the player is not going to move on to the next item.

Can’t observe AVPlayerItem for #“status” key

I’m trying to play stream from URL, but here is an issue. ObserveValueForKeyPath:ofObject:change:context just doesn’t execute. As I understand, it is not depends on streamURL, nether it is correct or not. It must change status to AVPlayerItemStatusReadyToPlay or AVPlayerItemStatusFailed from AVPlayerItemStatusUnknown. But nonetheless I checked that URL in browser, and it is working fine. So, what’s the problem? I watched WWDC video about it, and it says, if you have audio stream, use AVPLayerItem before AVAsset.
Here is my code:
- (void) prepare
{
NSURL * trackStreamURL = [NSURL URLWithString:streamURL];
NSLog(#"STREAM URL: %#",trackStreamURL);
_playerItem = [AVPlayerItem playerItemWithURL:trackStreamURL];
[_playerItem addObserver:self forKeyPath:#"status" options:0 context:nil];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(#"KEY PATH : %#", keyPath);
NSLog(#"CHANGE : %#", change);
}
Thanks in advance!
I've always observed the status property on the AVPlayer instead of the AVPlayerItem since you need a player to play the player item anyway. In fact, I had never even looked at the status property of the player item.
The status of the player item probably never changes because there is no player that is ready to play it. So, Create a player with the player item and observe the status of the player (or possibly, still the status of the player item).
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];

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.

AVPlayerItemStatusUnknown showing up when doing Live HTTP streaming

I am using AVPlayer to view videos stored on Amazon's CloudFront -- Live HTTP protocol is used and the playlist and segments are stored on S3 and hosted using CloudFront.
After playing a few videos I start getting a status of AVPlayerItemStatusUnknown from the AVPlayer item
AVPlayer.currentItem.status == AVPlayerItemStatusUnknown
This status persists when a new video playlist is selected -- I've tried de-allocating the AVPlayer before setting a new playlist URL and still the AVPlayerItemStatusUnknown status remains until I terminate the application.
Two questions. Is anybody using Amazaon CloudFront to host video experiencing the same issue? Does anybody know a work around so i can recover the state of the AVPlayer to prevent the user from having to terminate the app to view any more videos?
Many Thanks,
//aaron
For streaming media this looks like a normal behavior to me. Do you add an observer for the 'status' property? You should start playback when status changes to AVPlayerItemStatusReadyToPlay.
[item addObserver:self forKeyPath:#"status" options:0 context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:#"status"]) {
AVPlayerItem *item = (AVPlayerItem *)object;
if (item.status == AVPlayerItemStatusReadyToPlay) {
//Ready
}
}
}
I found the problem. Short answer is it was an over retained AVPlayer, which by the way, was not noticed by the Instruments tool using the leaks template. Sorry for the false alarm.
//aaron

Resources