[英]Control background music in Swift (macOS)
I am developing a macOS app that basically plays some sound in the background.我正在开发一个 macOS 应用程序,它基本上在后台播放一些声音。 The only issue that I have is that the audio plays from the App Delegate to keep it going when the app runs in background, however I do not know how to stop or play the audio from my View Controller.
我唯一的问题是应用程序在后台运行时从应用程序代表播放音频以使其继续运行,但是我不知道如何停止或播放来自我的视图 Controller 的音频。 In AppDelegate.swift:
在 AppDelegate.swift 中:
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var audioURL = URL(fileURLWithPath: Bundle.main.path(forResource: "audio", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
func applicationDidFinishLaunching(_ aNotification: Notification) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
audioPlayer.prepareToPlay()
audioPlayer.volume = 0.2
} catch {
print("Sorry, couldn't load the audio file")
}
}
I was thinking about using a delegate, but I am new both to UIs as well as C#/Swift, so I really don't know how to implement one.我正在考虑使用委托,但我对 UI 和 C#/Swift 都很陌生,所以我真的不知道如何实现它。
Your view controller can get a reference to the app delegate with您的观点 controller 可以通过以下方式获得对应用委托的引用
if let appDelegate = NSApp.delegate as? AppDelegate {
// do something with appDelegate.audioPlayer
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.