ios - AVAudioPlayer playing overtime viewcont. loads [Swift] -
in mainmenuviewcontroller in viewdidload
, tell play background song. problem is, when user goes view , goes main menu, starts playing song again, , 2 copies overlap. tried put in viewdidload
didn't work
if themeplayer.playing == false { themeplayer.preparetoplay() themeplayer.play() }
it kind of ignores if condition , plays anyways. how can fix this?
-viewdidload
run when view loaded. since player still playing song when navigate away mainmenuviewcontroller
indicates view controller never being deallocated. try putting if condition in -viewdidappear
or -viewwillappear
method.
override func viewwillappear(animated: bool) { super.viewwillappear(animated); if themeplayer == nil { // either it's first time view loaded, or themeplayer deallocated let soundurl = nsbundle.mainbundle().urlforresource("pres song", withextension: "mp3") themeplayer = avaudioplayer(contentsofurl: soundurl, error: nil) themeplayer.numberofloops = -1 themeplayer.volume = 0.1 themeplayer.preparetoplay() themeplayer.play() } if themeplayer.playing == false { themeplayer.preparetoplay() themeplayer.play() } }
if in doubt in future on if being called, use breakpoints , step through code.
Comments
Post a Comment