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

后端 未结 2 1892
粉色の甜心
粉色の甜心 2020-12-05 11:58

I\'ve created my own custom controls for use with the MPMoviePlayerController. So far everything works except the mute button control.

I\'ve configured

2条回答
  •  时光说笑
    2020-12-05 12:35

    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.

提交回复
热议问题