Disable Audio (and interruption) with MPMoviePlayerController using Swift

后端 未结 1 824
自闭症患者
自闭症患者 2021-02-06 13:36

At the moment, this is how I\'m playing a video on the subview of my UIViewController:

override func viewDidAppear(animated: Bool)  {
    let filePath = NSBundle         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 13:51

    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)
    }
    

    0 讨论(0)
提交回复
热议问题