如何使用swift切换到不同视图时连续播放背景音乐? [英] How can I continuously play background music while switching to different views using swift?

查看:184
本文介绍了如何使用swift切换到不同视图时连续播放背景音乐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对快速编码很新。我现在正在制作游戏,我添加了一些背景音乐,这一切都很好。我甚至想办法在切换到不同的视图时如何让音乐连续播放,但每次我回到主菜单视图,我告诉游戏开始播放背景音乐,它重新开始。我想要它做的是在用户启动应用程序时开始播放并保持循环直到用户关闭应用程序。我使用这段代码来启动背景音乐:

I'm pretty new to swift and coding in general. I'm making a game now and I've added some background music and that's all working fine. I even figured out how to have the music play continuously when switching to different views, but every time I go back to the 'main menu' view in which I told the game to start playing the background music, It start over again. What I want it to do is to start playing when the user starts up the app and keeps looping till the user closes the app. I used this bit of code to get the background music to start:

var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename:String){
let url = NSBundle.mainBundle()。 URLForResource(
filename,withExtension:nil)
if(url == nil){
println(找不到文件:(filename))
返回
}

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

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

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

}

我把这一点我的主视图控制器中的代码(这是人们在打开应用时看到的第一个屏幕)

var player = AVAudioPlayer()

if  player.playing {
    player.play()
} else {
    playBackgroundMusic("BackgroundMusic.m4a")
}

现在我虽然如此:如果音乐在播放,它会继续播放,ELSE开始播放音乐又来了。但是现在它只是开始播放音乐,即使音乐是在我来自的视图上播放的。我在其他2个视图中使用了这段代码来使音乐连续播放并且工作正常:

Now I though this: IF the music is playing, it continues playing and ELSE it start to play the music again. But now It just starts playing the music again even if the music was playing on the view I came from. I used this bit of code in the other 2 views to make the music play continuously by the way and it works fine:

func resumeBackgroundMusic() {
   if let player = backgroundMusicPlayer {
       if !player.playing {
           player.play()
       }
   }

}

推荐答案

你可以从AppDelegate开始和停止你的音乐...最好的方法是创建一个MusicPlayer类,在AppDelegate中实例化它并在其中调用start和stop方法......

You can start and stop your music from AppDelegate... The best way would be to create a MusicPlayer Class, instantiate it in AppDelegate and call start and stop methods in it...

你有足够的经验来写这样的东西吗?

Do you have enough experience to write something like that?

或者我应该帮你吗?

这篇关于如何使用swift切换到不同视图时连续播放背景音乐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆