我一直试图弄清楚如何停用播放声音。我尝试用声音动作附加一个removeAtionWithKey
,它似乎工作正常,但声音不会停止播放。这是因为我在SpriteKit
使用了行动吗?
如果这个问题在这里解决而不是导入AVFoundation
,那么你能给我一些例子来阻止声音被播放吗?或者,如果在这种情况下首选导入AVFoundation
,您是否也可以提供一些代码。
答案 0 :(得分: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()
^^!