【问题标题】:Control background music in Swift (macOS)在 Swift (macOS) 中控制背景音乐
【发布时间】:2020-06-15 15:34:02
【问题描述】:

我正在开发一个基本上在后台播放一些声音的 macOS 应用程序。我唯一的问题是应用程序在后台运行时从应用程序代理播放音频以使其继续运行,但是我不知道如何从我的视图控制器停止或播放音频。在 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 都很陌生,所以我真的不知道如何实现。

【问题讨论】:

    标签: swift macos delegates avaudioplayer


    【解决方案1】:

    您的视图控制器可以通过

    获取对应用委托的引用
    if let appDelegate = NSApp.delegate as? AppDelegate {
        // do something with appDelegate.audioPlayer
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多