2016-07-20 2 views
0

내 앱이 실행되는 동안 음악을 재생하기 위해이 코드를 작성했지만 다른 앱으로 이동하면 음악이 중지됩니다.앱이 백그라운드에있을 때 음악이 재생되지 않습니다. Swift Xcode

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    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) 
    } 
    playBackgroundMusic("anti.mp3") 


} 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

import AVFoundation 

var backgroundMusicPlayer = AVAudioPlayer() 

func playBackgroundMusic(filename: String) { 
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) 
    guard let newURL = url else { 
     print("Could not find file: \(filename)") 
     return 
    } 
    do { 
     backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL) 
     backgroundMusicPlayer.numberOfLoops = -1 
     backgroundMusicPlayer.prepareToPlay() 
     backgroundMusicPlayer.play() 
    } catch let error as NSError { 
     print(error.description) 
    } 
} 

필자는 필요한 배경 모드에서 info.plist에 오디오 문자열을 추가했습니다.

나는이 출력도 얻었으므로 다른 앱을 사용하는 동안 백그라운드에서 계속 재생할 것이라고 생각했지만 그렇지는 않습니다.

AVAudioSession Category Playback OK 
AVAudioSession is Active 
AVAudioSession Category Playback OK 
AVAudioSession is Active 

답변

1

확인 Audio,Airplay and picture in pictureproject setup

확인 화면에서 target에서 capabilities에서 background modes에 선택되어 있는지 확인

enter image description here

관련 문제