使用Swift禁用MPMoviePlayerController的音频(和中断)

时间:2014-06-22 13:54:46

标签: swift mpmovieplayercontroller avplayer avplayerlayer

目前,这就是我在UIViewController子视图上播放视频的方式:

override func viewDidAppear(animated: Bool)  {
    let filePath = NSBundle.mainBundle().pathForResource("musicvideo", ofType: "mp4")
    self.moviePlayerController.contentURL = NSURL.fileURLWithPath(filePath)
    self.moviePlayerController.play()
    self.moviePlayerController.repeatMode = .One
    self.moviePlayerController.view.frame = self.view.bounds
    self.moviePlayerController.scalingMode = .AspectFill
    self.moviePlayerController.controlStyle = .None
    self.moviePlayerController.allowsAirPlay = false
    self.view.addSubview(self.moviePlayerController.view)
}

我已经阅读了通过执行以下操作来禁用音频的方法(根本没有任何工作)。请记住,我试图禁用它,以便不通过音乐应用程序,Spotify等中断当前播放的音乐。

// Playing media items with the applicationMusicPlayer will restore the user's Music state after the application quits.

// The current volume of playing music, in the range of 0.0 to 1.0.
// This property is deprecated -- use MPVolumeView for volume control instead.

1)MPMusicPlayerController.applicationMusicPlayer().volume = 0

2)MPVolumeView甚至没有设置实际音量的设置?这是一个控制。

3)self.moviePlayerController.useApplicationAudioSession = false

1 个答案:

答案 0 :(得分:5)

所以我找到了this answer

这是我最终使用的Swift代码。然后我使用AVPlayerLayer作为子图层添加到视图中,这非常有效。

感谢OP成功获得Apple技术人员并提供原始Objective-C code

我现在面临的唯一问题是:

1)中断当前的音乐播放,无论是来自Music,Spotify等。

2)如果关闭应用并再次打开,视频就会停止播放。

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