//
//  ViewController.swift
//  PlayingAudio
//
//  Created by Keith Welch on 12/4/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {

    @IBOutlet weak var btnPlay: UIButton!
    @IBOutlet weak var btnStop: UIButton!
    @IBOutlet weak var sliderVolume: UISlider!
    
    var audioPlayer:AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        btnPlay.enabled = true
        btnStop.enabled = false
    }

    @IBAction func btnPlayTouched(sender: AnyObject) {
        let path = NSBundle.mainBundle().pathForResource("tune", ofType:"m4a")
        let url = NSURL.fileURLWithPath(path!)
        
        
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
            audioPlayer.volume = sliderVolume.value
            audioPlayer.delegate = self
            audioPlayer.play()
            
            btnStop.enabled = true
            btnPlay.enabled = false

        } catch {
            NSLog("Player not available")
        }
    }
    
    @IBAction func btnStopTouched(sender: AnyObject) {
        btnPlay.enabled = true
        btnStop.enabled = false
        if (audioPlayer.playing) {
            audioPlayer.stop()
        }
    }
    
    @IBAction func VolumeChanged(sender: AnyObject) {
        if (audioPlayer != nil)
        {
            audioPlayer.volume = sliderVolume.value
        }
    }
    
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        btnPlay.enabled = true
        btnStop.enabled = false
    }
    
    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
        btnPlay.enabled = true
        btnStop.enabled = false
        NSLog(error!.description)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

