Search code examples
swiftaudioavaudioplayer

Swift: Audio start and stop in .1 second


I've followed every post on Net but none solved this issue. The sound start and stop right immediately like after 0.1 second. I can hear a sound very quickly.

here is my code from where it matters: ...

    let path = NSBundle.mainBundle().pathForResource("bgMusic", ofType: "mp3")
    let bgMusicURL = NSURL.fileURLWithPath(path!)

    var backgroundMusicPlayer:AVAudioPlayer!

    do{
        try AVAudioSession.sharedInstance().setActive(true)
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL)
        backgroundMusicPlayer!.prepareToPlay()
        backgroundMusicPlayer!.play()

    }catch {
        print ("ERROR")
    }

...


Solution

  • When the function that contains your code snippet ends, the garbage collector will come to deallocate your backgroundMusicPlayer. Try either making backgroundMusicPlayer a global variable, or having some kind of static variable that holds it.