背景Swift中的AVAudioSession / AVQueuePlayer / AVAudioPlayer

时间:2016-07-05 23:33:40

标签: ios swift avaudioplayer avaudiosession avqueueplayer

问题:即使应用程序在后台,我也试图让我的音频继续播放。期望的结果是即使在以下情况下音频仍继续播放:按下主页按钮,电话睡眠/被锁定,并且能够与其他声音(本地音乐应用等)混合。我查看了其他示例并尝试实现它们但没有成功。启动应用程序操作后,我的应用程序播放一个短暂的声音,然后等待一段时间,然后播放另一个声音。

我尝试过的事情 -

  1. AVAudioPlayer not responding in the background
  2. How to Play Audio in Background Swift?
  3. 到目前为止我学到的东西是我可能想要将AVAudioSession与Ambient类别一起使用,以便我的声音与原生音乐应用程序混合。我已在选项卡和plist中打开了背景功能。我已经尝试将AVAudioSession放在多个位置(委托/ VC文件)。

    我正在使用#2中的代码来启动我的audioSession。这是播放声音的代码

    func playComboSound(fileName:String){
        if(fileName != "burpees" && fileName != "pushUps" && fileName != "sitUps")
        {
            let url = NSBundle.mainBundle().URLForResource(fileName, withExtension: "mp3")!
            do {
                appDelegate.audioPlayer = try AVAudioPlayer(contentsOfURL: url)
                //guard let appDelegate.audioPlayer = audioPlayer else { return }
                //appDelegate.audioPlayer!.stop()
                appDelegate.audioPlayer!.prepareToPlay()
                appDelegate.audioPlayer!.play()
            } catch let error as NSError {
            print(error.description)
        }
        }
        else
        {
            let numRepAudio: String
            switch numReps{
                case "THREE":
                    numRepAudio = "three"
                case "FIVE":
                    numRepAudio = "five"
                case "TEN":
                    numRepAudio = "ten"
                default:
                    numRepAudio = "three"
            }
    
            let url1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(numRepAudio, ofType: "mp3")!)
            let url2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fileName, ofType: "mp3")!)
            print(numRepAudio)
            print(fileName)
            let item1 = AVPlayerItem(URL: url1)
            let item2 = AVPlayerItem(URL: url2)
            let items: [AVPlayerItem] = [item1, item2]
            appDelegate.playerQueue = AVQueuePlayer(items: items)
            appDelegate.playerQueue!.play()
        }
    }
    

    谢谢

0 个答案:

没有答案