gpt4 book ai didi

ios - 场景更改后音乐停止播放 SKAudioNode Xcode 8

转载 作者:行者123 更新时间:2023-11-29 00:29:42 25 4
gpt4 key购买 nike

所以我一直试图让这个音频文件在游戏的所有场景中播放,但它在 MenuScene 之后中断了。我从 GameViewController

调用 MenuScene
class GameViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

if let view = self.view as! SKView? {
// Load the SKScene from 'MenuScene.sks'
if let scene = SKScene(fileNamed: "MenuScene") {
// Set the scale mode to scale to fit the window

然后在 MenuScene 中,我通过这样做开始播放音乐。

class MenuScene: SKScene {

var starfield:SKEmitterNode!

var newGameButtonNode:SKSpriteNode!
var difficultyButtonNode:SKSpriteNode!
var difficultyLabelNode:SKLabelNode!
var backgroundMusic:SKAudioNode!

override func didMove(to view: SKView) {


let backgroundMusic = SKAudioNode(fileNamed: "Snap.mp3")
backgroundMusic.autoplayLooped = true
addChild(backgroundMusic)

音乐开始播放。然后我在 touchesBegan () 中,如果触摸 GameScene 按钮,它将加载该场景。我将过渡做得非常长,以找出音乐何时停止并在整个过渡过程中播放,但是当加载 GameScene 时,它​​就会停止。

if nodesArray.first?.name == "newGameButton" {

let transition = SKTransition.fade(withDuration: 5.0)

run(SKAction.wait(forDuration: 5.0), completion: {
self.backgroundMusic = SKAudioNode(fileNamed: "Snap.mp3")
self.backgroundMusic.autoplayLooped = true
self.addChild(self.backgroundMusic)
})
let gameScene = GameScene(size: self.size)

self.view!.presentScene(gameScene, transition: transition)

我希望它在整个游戏过程中和 GameOver 场景中继续播放并永远循环播放。

最佳答案

确保您在主 SKScene 中并且

你可以这样做:

self.runAction(SKAction.playSoundFileNamed("YourFileName.extension", waitForCompletion: false))

重复音乐:

SKAction.repeatForever(SKAction.playSoundFileNamed("YourFileName.extension", waitForCompletion: true))

您的音乐将继续播放..

With AVFoundation

我已经完成的代码之一。

import AVFoundation


var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}

var error: NSError? = nil
backgroundMusicPlayer =
AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
print("Could not create audio player: \(error!)")
return
}

backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}

import SpriteKit

关于ios - 场景更改后音乐停止播放 SKAudioNode Xcode 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com