简体   繁体   English

应用程序在后台Swift Xcode不能播放音乐

[英]Music not playing when app is in the background Swift Xcode

I've written this code to play music while my app runs but when I go to another app the music stops. 我已经编写了这段代码来在我的应用程序运行时播放音乐,但是当我转到另一个应用程序时,音乐就会停止。

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

I also added the audio string in the info.plist under required background modes. 我还在所需的背景模式下在info.plist中添加了音频字符串。

I get this output as well, so I thought it would continue playing in the background while using other apps but it does not. 我也得到了此输出,因此我认为在使用其他应用程序时它将继续在后台播放,但事实并非如此。

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

Make sure that Audio,Airplay and picture in picture is checked in background modes under capabilities under target under project setup 确保在background modes下在project setuptarget下的capabilities下检查Audio,Airplay and picture in picture

Check the screenshot 检查截图

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM