1
我目前使用以下代碼在我的Xcode項目中播放音樂。但是,當我播放音樂時,其他音樂應用程序(例如:spotify)停止播放。我知道有AVAudioSessionCategoryAmbient,但我不確定如何在我的代碼中設置此功能。從應用程序播放音樂時在Xcode中播放聲音
如何在我的應用程序內播放音樂而不停止其他正在播放的應用程序的音樂?
任何幫助將不勝感激:D
謝謝!
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()
}
}
太棒了!這很容易哈哈感謝您的幫助!乾杯! :D:D:D – Questions