在XCODE 8/Swift 3和Spritekit上,我正在播放背景音乐(5分钟的歌曲),从GameViewController的ViewDidLoad (来自所有场景的父场景,而不是特定的GameScene)调用它,因为我希望它在整个场景更改过程中不间断地播放。这是没有问题的。
但我的问题是,当我在一个场景中时,我如何随心所欲地停止背景音乐呢?比如说,当用户在第三场比赛中得到一个特定的分数时?因为我不能访问父文件的方法。下面是我用来调用音乐播放的代码:
类GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var audioPlayer = AVAudioPlayer()
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print (error)
}
audioPlayer.play()非常感谢你的帮助
发布于 2016-11-01 13:51:06
为什么不创建一个可以从任何地方访问的音乐助手类呢?单例方法或具有静态方法的类。这也会使您的代码更简洁、更易于管理。
我还会拆分安装方法和play方法,这样每次播放文件时都不会设置播放机。
例如,辛格尔顿
class MusicManager {
static let shared = MusicManager()
var audioPlayer = AVAudioPlayer()
private init() { } // private singleton init
func setup() {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print (error)
}
}
func play() {
audioPlayer.play()
}
func stop() {
audioPlayer.stop()
audioPlayer.currentTime = 0 // I usually reset the song when I stop it. To pause it create another method and call the pause() method on the audioPlayer.
audioPlayer.prepareToPlay()
}
}当您的项目启动时,只需调用安装方法
MusicManager.shared.setup()在你的项目中任何地方你都可以说
MusicManager.shared.play()去演奏音乐。
要想停止它,只需调用停止方法
MusicManager.shared.stop()要获得更多功能丰富的多声道示例,请查看GitHub上的“我的助手”
https://github.com/crashoverride777/SwiftyMusic
希望这能有所帮助
https://stackoverflow.com/questions/40296793
复制相似问题