2016-06-11 10 views
0

私はAVPlayerの設定を持っていますが、電話がロックされているときやホーム画面でビデオのオーディオを再生し続けるようです。私はinfo.plistを編集し、オーディオバックグラウンドモードを有効にしましたが、いくつかのコードを追加する必要があると思います。私を助けてくれますか?おかげXcode swift - バックグラウンドモード - ロックされたAVPlayerのオーディオ

ここでは私のコードです:

輸入のUIKit 輸入AVFoundation 輸入AVKit

クラスのViewController:のUIViewController {

@IBAction func WarmUp(sender: UIButton) 
{ 
    WarmUpVideo() 
} 

func WarmUpVideo() 
{ 
    let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "MOV") 
    let videoURL = NSURL(fileURLWithPath: filePath!) 

    let player = AVPlayer(URL: videoURL) 
    let playerViewController = AVPlayerViewController() 

    playerViewController.player = player 

    self.presentViewController(playerViewController, animated: true) {() -> Void in playerViewController.player!.play() 
    } 

} 

func playExternalVideo() 
{ 

}

@IBAction func CoolDown(sender: UIButton) 
{ 
    CoolDownVideo() 
} 

func CoolDownVideo() 
{ 
    let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "mp4") 
    let videoURL = NSURL(fileURLWithPath: filePath!) 

    let player = AVPlayer(URL: videoURL) 
    let playerViewController = AVPlayerViewController() 

    playerViewController.player = player 

    self.presentViewController(playerViewController, animated: true) {() -> Void in playerViewController.player!.play() 
    } 

} 

}

答えて

2

私は次のコードが欠落していると思う:

do { 
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
    print("AVAudioSession Category Playback OK") 
    do { 
     try AVAudioSession.sharedInstance().setActive(true) 
     print("AVAudioSession is Active") 
    } catch let error as NSError { 
     print(error.localizedDescription) 
    } 
} catch let error as NSError { 
    print(error.localizedDescription) 
} 

は、あなたのviewDidLoadにこれを追加します。

+0

素晴らしいですが、問題があります:デバイスをロックすると再生が続行されますが、ホームボタンを使用してバックグラウンドに移動すると停止します。ここにアドバイスはありますか?ありがとう! –

+0

オーディオのバックグラウンドモードを有効にする必要があります。ターゲット>機能>背景モード>オーディオ、AirPlayなどとターゲット>機能>アプリケーション間オーディオ。これらの両方を有効にしました – Jad

+0

はい、これらの設定は不運に追加されました:(画面がロックされていてもアプリがフォアグラウンドになっていないときは再生されます) –

関連する問題