【问题标题】:Music not playing when app is in the background Swift Xcode应用程序在后台Swift Xcode时不播放音乐
【发布时间】:2016-07-20 11:59:15
【问题描述】:

我编写了这段代码来在我的应用程序运行时播放音乐,但是当我转到另一个应用程序时,音乐停止了。

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

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    确保Audio,Airplay and picture in picturecapabilitiestargetproject setup 下签入background modes

    查看截图

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多