我在Swift中有一个macOS(不是iOS)项目。
在我的主AppDelegate.swift中,我实例化一个名为PlaySound的类,然后调用startSound()
名为PlaySound.swift的类播放mp3。但是,除非我在任何一个类文件中调用play后立即进入sleep(),否则我听不到声音。我以为我正在失去对类实例化的引用,但是我可以调用一个测试打印函数,如你所见,并且有效。
有谁知道音频停止的原因?
感谢您的帮助 - 比尔
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let myCheck = PlaySound()
myCheck.startSound()
sleep(7)
myCheck.testPrint()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
下面的PlaySound课程......
import Foundation
import AVKit
class PlaySound {
var soundFile = "crickets"
var myPlayer = AVAudioPlayer()
func startSound() {
do {
self.myPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: soundFile, ofType: "mp3")!))
//set the number of loops to "infinite"
self.myPlayer.numberOfLoops = -1
self.myPlayer.prepareToPlay()
//set the volume to muted
self.myPlayer.volume = 0
//play the sound
self.myPlayer.play()
//fade in the sound
self.myPlayer.setVolume(1, fadeDuration: 2)
}
catch {
print(error)
}
} // end of startSound
func fadeOutSound() {
myPlayer.setVolume(0, fadeDuration: 10)
myPlayer.stop()
}
func testPrint() {
print("yes this works")
}
} // end of aclass
答案 0 :(得分:0)
applicationDidFinishLaunching
完成后,myCheck
超出范围并被取消初始化,因此没有任何声音可播放。您可以像这样将其保存在内存中:
class AppDelegate: NSObject, NSApplicationDelegate {
let myCheck = PlaySound()
func applicationDidFinishLaunching(_ aNotification: Notification) {
myCheck.startSound()
}
}