1

I have a file on documents folder of app and I want to play it.

if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
    let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
    do {
        let player = try AVAudioPlayer(contentsOfURL:url)
        player.prepareToPlay()
        player.play()
    }
    catch let error as NSException {
        print(error)
    }
    catch {}
}

There is a file on file system and I checked its existence. Also all lines in do block are executed. There is neither exception nor error and still no sound is played. What are possible problems and how can I solve them?

juanjo
  • 3,737
  • 3
  • 39
  • 44
aakpro
  • 1,538
  • 2
  • 19
  • 53

1 Answers1

8

You should make audioPlayer an instance variable global. This code will have it deallocated immediately after calling .play()

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        if NSFileManager.defaultManager().fileExistsAtPath(pathString){
        let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
}
}
Rahul Patel
  • 1,822
  • 12
  • 21
  • Not working yet! Do you have any idea how to understand what problem is? Or how to debug it? – aakpro Jul 01 '16 at 19:24
  • Are you certain you changed audioPlayer to be global? It should work like this... – FredericP Jul 01 '16 at 23:12
  • BTW, you'll have to learn and understand local and global variables, and memory management in Swift... Good luck! – FredericP Jul 02 '16 at 05:56
  • In this snippet, aren't you creating the audio player twice? Once at view instantiation and a 2nd time when the view calls viewDidLoad. If so, how would you do this so that it is instantiated just once? – AlvinfromDiaspar Nov 08 '16 at 21:02
  • @AlvinfromDiaspar try writing `var audioPlayer : AVAudioPlayer!` instead of `'var audioPlayer = AVAudioPlayer()` – Rahul Patel Nov 09 '16 at 07:59