macOS上的swift:AVAudioPlayer立即停止

问题描述 投票:0回答:1

我在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
swift xcode macos avaudioplayer macos-sierra
1个回答
0
投票

applicationDidFinishLaunching完成后,myCheck超出范围并被取消初始化,因此没有任何声音可播放。您可以像这样将其保存在内存中:

class AppDelegate: NSObject, NSApplicationDelegate {

    let myCheck = PlaySound()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        myCheck.startSound()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.