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

2

10

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.

Adorne answered 11/4, 2013 at 12:21 Comment(0)
A
10

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.

Adorne answered 19/4, 2013 at 11:15 Comment(5)
Would like to see that class, did you ever put it on GH?Preconception
Afraid not, I'm not 100% sure how stable my implementation is so I never got around to putting it up. Maybe I'll put it up just as a reference. One major flaw which I also discovered with this technique is that if you use this to control the value level (instead of just muting) it will only allow you to control the 0-100% of the set device volume level. For example say the device volume is set to 50% and you then use this method to reduce the app volume by 50% what you will actually hear is 25% volume.Adorne
ok, interesting. thanks for the reply. i'll probably go with the switch to AVPlayer to get .mutePreconception
@Camsoft: Thank you so much for providing this answer. It fixed my issue I was having with MPMovieController over here: #24352435Fives
From iOS 7 onwards, you can use the muted property of AVPlayer to mute the audio, instead of jumping through all those hoops with the mix stuff.Unmanly
S
4

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.

Smite answered 5/8, 2014 at 17:58 Comment(1)
It's an interesting way to handle it, but if the user has music playing in the background they will definitely notice it. Just FYI.Longevity

© 2022 - 2024 — McMap. All rights reserved.