【问题标题】:How to deactivate playing a sound如何停用播放声音
【发布时间】:2016-05-01 04:13:01
【问题描述】:

我一直在试图弄清楚如何停用播放声音。我尝试用声音动作附加removeAtionWithKey,它似乎工作正常,但声音并没有停止播放。这是因为我在SpriteKit 中使用了操作吗?

如果这个问题在这里解决而不是导入AVFoundation,那么你能给我一些例子来停止播放声音吗?或者,如果在这种情况下首选导入AVFoundation,您能否也提供一些代码。

【问题讨论】:

    标签: swift skaction playsound


    【解决方案1】:

    这是一个如何使用 AVFoundation 的示例。

    import Foundation
    import AVFoundation
    
    var backgroundMusicPlayer: AVAudioPlayer!
    
    func playBackgroundMusic(filename: String) {
    
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")
    
        if (url == nil) {
            print("Could not find the file \(filename)")
        }
    
        do { backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) } catch let error as NSError { print(error.debugDescription)}
    
        if backgroundMusicPlayer == nil {
            print("Could not create audio player")
        }
    
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    }
    
    var Sound: AVAudioPlayer!
    
    func playSound(filename: String) {
    
        let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "wav")
    
        if (url == nil) {
            print("Could not find the file \(filename)")
        }
    
        do { Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) } catch let error as NSError { print(error.debugDescription)}
    
        if Sound == nil {
            print("Could not create audio player")
        }
    
        Sound.prepareToPlay()
        Sound.play()
    }
    

    这就是你想要达到的目标(如果我理解得很好的话):

    @IBAction func MusicButton(sender: UIButton) {
        if backgroundMusicPlayer.playing {
            backgroundMusicPlayer.stop()
        }
        else {
            playBackgroundMusic("SomeMusicName")
        }
    }
    

    使用 AVFoundation 停止音乐就像 .stop() ^^!

    【讨论】:

    • 谢谢!!但是这些代码在我的源代码中效果不佳。在 GameStartScene 文件中,我设置了声音。转换到 GameScene 文件并触摸屏幕后,我想丢弃声音。所以,我在我的 GameScene 中尝试的是在 GameStartScene 中,'var Sound: AVFoudation'。在 GameScene 中,'var gameStartScene: GameStartScene!'里面开始触摸,gameStartScene.Sound.stop()。它看起来不错,但代码似乎不接受我的努力.....为什么这是一个错误???我无法弄清楚如何处理这个问题。如果您对此解决方案有一些想法,那将非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多