ios - Play background music in app? -


i want user able open app , have music start playing. want user able go view controller , return initial 1 without music stopping. want loop indefinitely.

i have tried put in viewdidload method of initial view controller start playing. happens is, user leaves initial view controller , when come back, music starts playing again, overlapping original copy.

to remedy this, put if statement checking if sound playing not launch copy , viewdidload method ignores if statement , plays again anyways. tried using viewdid/willappear. have tried putting sound in app delegate in applicationdidlaunchwithoptions method , got complete silence.

using singleton works well:

import avfoundation  class musichelper {     static let sharedhelper = musichelper()     var audioplayer: avaudioplayer?      func playbackgroundmusic() {         let asound = nsurl(fileurlwithpath: nsbundle.mainbundle().pathforresource("coolsong", oftype: "mp3")!)         {             audioplayer = try avaudioplayer(contentsofurl:asound)             audioplayer!.numberofloops = -1             audioplayer!.preparetoplay()             audioplayer!.play()         } catch {             print("cannot play file")         }     } } 

then can use class (as per swift 2.1)

musichelper.sharedhelper.playbackgroundmusic() 

Comments