关于swift:在播放来自应用程序的音乐时播放Xcode中的声音

Playing sounds in Xcode while playing music from apps

我目前正在使用以下代码在Xcode项目中播放音乐。但是,当我播放音乐时,其他音乐应用程序(例如Spotify)停止播放。我知道这里有AVAudioSessionCategoryAmbient,但是我不确定如何在代码中设置此功能。

如何在不停止当前正在播放的其他应用程序的音乐的情况下在我的应用程序中播放音乐?

任何帮助将不胜感激:D

谢谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import UIKit

import AVFoundation


let appDelegate = UIApplication.shared.delegate as! AppDelegate

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


  /* MUSIC */

var musicIsPlaying: Bool = false
var bgMusicLoop: AVAudioPlayer!

func playBackgroundMusic(fileName: String, withExtenstion fileExtension: String) {


    let appDelegate = UIApplication.shared.delegate as! AppDelegate


    if appDelegate.musicIsPlaying == false {

        appDelegate.musicIsPlaying = true

        let filePath: String = Bundle.main.path(forResource: fileName, ofType: fileExtension)!

        if (appDelegate.bgMusicLoop != nil) {
            appDelegate.bgMusicLoop.stop()
        }
        appDelegate.bgMusicLoop = nil

        do {

            appDelegate.bgMusicLoop = try AVAudioPlayer(contentsOf: NSURL.fileURL(withPath: filePath))

        } catch {
            print(error)
        }

        //A negative means it loops forever
        appDelegate.bgMusicLoop.numberOfLoops = -1
        appDelegate.bgMusicLoop.prepareToPlay()
        appDelegate.bgMusicLoop.play()
    }
}

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)添加到您的代码中。

AVAudioSessionCategoryAmbient"播放声音,这些声音会增加光泽或趣味性,但对应用程序的使用并非必不可少。"