Disable Audio (and interruption) with MPMoviePlayerController using Swift

拥有回忆 提交于 2019-12-03 03:45:06
fuzz

So I found this answer.

This is my Swift code that I ended up going with. I then used an AVPlayerLayer to add to the view as a sublayer, which works perfectly.

Thanks to the OP who managed to get a hold of an Apple technician and provided the original Objective-C code.

The only problems I'm facing now is that it:

1) Interrupts current music playback, whether it's from Music, Spotify, etc.

2) Video stops playing if I close the app and open it up again.

override func viewDidAppear(animated: Bool)  {
    let filePath = NSBundle.mainBundle().pathForResource("musicvideo", ofType: "mp4")

    var asset: AVURLAsset?
    asset = AVURLAsset.URLAssetWithURL(NSURL.fileURLWithPath(filePath), options: nil)
    var audioTracks = NSArray()
    audioTracks = asset!.tracksWithMediaType(AVMediaTypeAudio)

    // Mute all the audio tracks
    let allAudioParams = NSMutableArray()
    for track: AnyObject in audioTracks {
        // AVAssetTrack
        let audioInputParams = AVMutableAudioMixInputParameters()
        audioInputParams.setVolume(0.0, atTime: kCMTimeZero)
        audioInputParams.trackID = track.trackID
        allAudioParams.addObject(audioInputParams)
    }

    let audioZeroMix = AVMutableAudioMix()
    audioZeroMix.inputParameters = allAudioParams

    // Create a player item
    let playerItem = AVPlayerItem(asset: asset)
    playerItem.audioMix = audioZeroMix

    // Create a new Player, and set the player to use the player item
    // with the muted audio mix
    let player = AVPlayer.playerWithPlayerItem(playerItem) as AVPlayer

    player.play()

    let layer = AVPlayerLayer(player: player)
    player.actionAtItemEnd = .None

    layer.frame = self.view.bounds
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.addSublayer(layer)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!