How can I continuously play background music while switching to different views using swift?

℡╲_俬逩灬. 提交于 2019-12-11 09:43:45

问题


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("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()

}

And I put this bit of code in my Home View Controller (Which is the first screen people see when opening up the app)

var player = AVAudioPlayer()

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

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()
       }
   }

}


回答1:


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?

Or should I help you?



来源:https://stackoverflow.com/questions/27627769/how-can-i-continuously-play-background-music-while-switching-to-different-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!