swift - 在 Swift (macOS) 中控制背景音乐
问题描述
我正在开发一个 macOS 应用程序,它基本上在后台播放一些声音。我唯一遇到的问题是,当应用程序在后台运行时,音频会从 App Delegate 播放以使其继续运行,但是我不知道如何停止或播放来自 View Controller 的音频。在 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")
}
}
我正在考虑使用委托,但我对 UI 和 C#/Swift 都很陌生,所以我真的不知道如何实现它。
解决方案
您的视图控制器可以通过以下方式获取对应用委托的引用
if let appDelegate = NSApp.delegate as? AppDelegate {
// do something with appDelegate.audioPlayer
// ...
}
推荐阅读
- php - 会话值到数组
- python - 如何在 JSON 文件中按字母顺序按一个字符串对列表进行排序
- html - 如何解决具有背景 div 的 2 列布局中的高度自动问题
- python - 将 Selenium CSV 下载到 python 变量中
- python - 将高度作为值放入另一列
- c# - 在 C# 中使用 APNS 推送进行编码
- javascript - TypeError:无法读取未定义的属性“oldRole”
- angular - 返回成功的 Observable On Route Resolve Call Failure?
- python-3.x - 数据包生成脚本的优化
- machine-learning - 用于 MLP Keras 预测的循环程序