ios - SwiftySound 在 Swift 中不起作用

标签 ios swift

我使用 SwiftySound 在我的应用程序(射击游戏)上实现了声音效果。 但如果设置了触摸目标时的声音,有时声音不会播放。
不知道为什么有时候能播放有时候不能。

代码:

class ViewController: ViewController {

    var soundManager: SoundManager = SoundManager()

    //.....

    func touchedTarget(){
        soundManager.playSE()
    }
}

class SoundManger {

    let tapSE: Sound = Sound(url:Bundle.main.url(forResource: "tap", withExtension: "mp3")!)!

    init(){

    }

    func playSE {
       tapSE.play(numberOfLoops: 0, completion: nil)
    }
}

编辑

1.在“playSE”中添加了“DispatchQueue.main.async{},但不起作用。

func playSE {
    DispatchQueue.main.async {
        tapSE.play(numberOfLoops: 0, completion: nil)
    }
}

2.在“touchedTarget()”中添加了“DispatchQueue.main.async{},但不起作用。

func touchedTarget(){
    DispatchQueue.main.async {
        soundManager.playSE()
    }
}

最佳答案

问题可能是您可能在后台线程上调用它,而它应该在主线程上。

在你的 View Controller 或任何你调用声音的地方尝试使用:

DispatchQueue.main.async {
    SoundManager().playSE()     
}

关于ios - SwiftySound 在 Swift 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50600121/

相关文章:

ios - UIImagePicker 不允许编辑图像

ios - Swift 错误 - 使用未声明的类型 'cell' - Collection View

json - SwiftUI:尝试加载本地 JSON 数据时,我在 Canvas 中收到预览错误

ios - 从 JSON 图像 url swift 填充 collectionView

ios - 如何访问变量名称并将字符串更改为它

ios - 如何替换字符串中的所有元音?

ios - NSObjectInaccessibleException',原因 : 'CoreData could not fulfill a fault

ios - 标签栏导航应用程序中的按钮编程

swift - 无法向服务 com.apple.WebKit.WebContent : 113: Could not find specified service _after_ implementing AdMob 发出信号

ios - SKShapeNode 使用错误的宽度和高度