2016-04-21 83 views
1

我一直在試圖找出如何停用播放聲音。我試圖用一個合理的動作附加removeAtionWithKey,它似乎工作正常,但聲音不停止播放。這是因爲我在SpriteKit中使用動作嗎?如何取消激活播放聲音

如果這個問題在這裏得到解決,而不是導入AVFoundation,那麼你能給我舉一些例子來阻止播放聲音嗎?或者,如果在這種情況下首選導入AVFoundation,您是否也可以向我提供一些代碼。

回答

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()容易^^!

+0

謝謝!但是這些代碼在我的源代碼中效果不好。在GameStartScene文件中,我設置了聲音。在轉換到GameScene文件並觸摸屏幕後,我想放棄聲音。所以,我在GameScene中嘗試的是在GameStartScene中,'var Sound:AVFoudation'。 Iin GameScene,'var gameStartScene:GameStartScene!'觸摸開始後,gameStartScene.Sound.stop()。它看起來很好,但代碼似乎不接受我的努力.....爲什麼這是一個錯誤?我無法弄清楚如何處理這個問題。如果你對這個解決方案有一些想法,這是非常有幫助的。 – bagels

+0

哦,現在我明白了。按照我想要的方式工作!大人們感謝! – bagels

+0

我很樂意提供幫助:D我提出了你的問題;) – Coder1000