Search code examples
iphoneiosmpmovieplayercontrolleravaudioplayer

How to mute video while playing an mp3 with AVAudioPlayer


I have a video with audio, and an mp3. I would like to play the video in mute (audio off) while playing an mp3. I am using MPMoviePlayerController to play the video, and AVAudioPlayer to play the mp3. Is there a way to do it?


Solution

  • I chose to answer my own question: @nickbona answer was fine but it has no simple and example code. So the solution is to use AVPlayer instead of MPMoviePlayerController.

    So here I am with an easy source code example if someone else will need it:

    //init player
    AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"yourfile" ofType:@"mp4"]] options:nil];
    AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *myPlayerController = [AVPlayer playerWithPlayerItem:anItem];
    
    //disable audio (this is the version when you have more than one video in the playlist: i write this version so it should be more useful)
    NSArray *playerTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
    NSMutableArray *playerParams = [NSMutableArray array];
    for (AVAssetTrack *track in playerTracks) {
        AVMutableAudioMixInputParameters *audioInputParams =    [AVMutableAudioMixInputParameters audioMixInputParameters];
        [audioInputParams setVolume:0.0 atTime:kCMTimeZero];
        [audioInputParams setTrackID:[track trackID]];
        [playerParams addObject:audioInputParams];
    }
    AVMutableAudioMix *muteAudioMix = [AVMutableAudioMix audioMix];
    [muteAudioMix setInputParameters:playerParams];
    [[myPlayerController currentItem] setAudioMix:muteAudioMix];
    

    Hope it can help.