13장 음악 재생하고 녹음하기







//

//  ViewController.swift

//  Audio

//

//  Created by stayfoolish on 20/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import AVFoundation


class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {

    

    var audioPlayer: AVAudioPlayer!

    var audioFile: URL!

    var MAX_VOLUME: Float = 10.0

    var progressTimer: Timer!

    

    let timePlayerSelector:Selector = #selector(ViewController.updatePlayTime)

    let timeRecordSelector:Selector = #selector(ViewController.updateRecordTime)


    @IBOutlet var pvProgressPlay: UIProgressView!

    @IBOutlet var lblCurrentTime: UILabel!

    @IBOutlet var lblEndTime: UILabel!

    @IBOutlet var btnPlay: UIButton!

    @IBOutlet var btnPause: UIButton!

    @IBOutlet var btnStop: UIButton!

    @IBOutlet var slVolume: UISlider!

    

    @IBOutlet var btnRecord: UIButton!

    @IBOutlet var lblRecordTime: UILabel!

    

    var audioRecorder: AVAudioRecorder!

    var isRecordMode = false

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

       selectAudioFile()

        if !isRecordMode {

            initPlay()

            btnRecord.isEnabled = false

            lblRecordTime.isEnabled = false

        }else {

            initRecord()

        }

        

    }

    

    func selectAudioFile(){

        if !isRecordMode{

             audioFile = Bundle.main.url(forResource: "Sicilian_Breeze", withExtension: "mp3")

        }else {

            let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

            audioFile = documentDirectory.appendingPathComponent("recordFile.m4a")

        }

    }

    

    func initRecord(){

        let recordSettings = [

            AVFormatIDKey : NSNumber(value: kAudioFormatAppleLossless as UInt32),

            AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,

            AVEncoderBitRateKey : 320000,

            AVNumberOfChannelsKey : 2,

        AVSampleRateKey: 44100.0] as [String : Any]

        do {

            audioRecorder = try AVAudioRecorder(url: audioFile, settings: recordSettings)

        }catch let error as NSError {

            print("Error-initRecord : \(error)")

        }

        audioRecorder.delegate = self

        audioRecorder.isMeteringEnabled = true

        audioRecorder.prepareToRecord()

        

        slVolume.value = 1.0

        audioPlayer.volume = slVolume.value

        lblEndTime.text = convertNSTimeInterval2String(0)

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(false, pause: false, stop: false)

        

        let session = AVAudioSession.sharedInstance()

        do {

            try session.setCategory(AVAudioSessionCategoryPlayAndRecord)

        }catch let error as NSError {

            print(" Error-setCategory : \(error)")

        }

        do {

            try session.setActive(true)

        }catch let error as NSError {

            print(" Error-setActive : \(error)")

        }

    }

    

    func initPlay(){

        do {

            audioPlayer = try AVAudioPlayer(contentsOf: audioFile)

        }catch let error as NSError {

            print("Error-initPlay : \(error)")

        }

        slVolume.maximumValue = MAX_VOLUME

        slVolume.value = 1.0

        pvProgressPlay.progress = 0

        

        audioPlayer.delegate = self

        audioPlayer.prepareToPlay()

        audioPlayer.volume = slVolume.value

        lblEndTime.text = convertNSTimeInterval2String(audioPlayer.duration)

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(true, pause: false, stop: false)

/*

        btnPlay.isEnabled = true

        btnPause.isEnabled = false

        btnStop.isEnabled = false

 */

    }

    

    func convertNSTimeInterval2String(_ time:TimeInterval) -> String {

        let min = Int(time/60)

        let sec = Int(time.truncatingRemainder(dividingBy: 60))

        let strTime = String(format: "%02d:%02d", min, sec)

        return strTime

    }

    

    func setPlayButtons(_ play: Bool , pause: Bool, stop: Bool){

        btnPlay.isEnabled = play

        btnPause.isEnabled = pause

        btnStop.isEnabled = stop

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func btnPlayAudio(_ sender: UIButton) {

        audioPlayer.play()

        setPlayButtons(false, pause: true, stop: true)

        progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: timePlayerSelector, userInfo: nil, repeats: true)

    }

    

    @objc func updatePlayTime() {

        lblCurrentTime.text = convertNSTimeInterval2String(audioPlayer.currentTime)

        pvProgressPlay.progress = Float(audioPlayer.currentTime/audioPlayer.duration)

    }

    

    @IBAction func btnPauseAudio(_ sender: UIButton){

        audioPlayer.pause()

        setPlayButtons(true, pause: false, stop: true)

    }

    @IBAction func btnStopAudio(_ sender: UIButton){

        audioPlayer.stop()

        audioPlayer.currentTime = 0

        lblCurrentTime.text = convertNSTimeInterval2String(0)

        setPlayButtons(true, pause: false, stop: false)

        progressTimer.invalidate()

        

    }

    @IBAction func slChangeVolume(_ sender: UISlider) {

        audioPlayer.volume = slVolume.value

    }

    

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {

        progressTimer.invalidate()

        setPlayButtons(true, pause: false, stop: false)

    }

    @IBAction func swRecordMode(_ sender: UISwitch) {

        if sender.isOn{

            audioPlayer.stop()

            audioPlayer.currentTime = 0

            lblRecordTime!.text = convertNSTimeInterval2String(0)

            isRecordMode = true

            btnRecord.isEnabled = true

            lblRecordTime.isEnabled = true

        }else {

            isRecordMode = false

            btnRecord.isEnabled = false

            lblRecordTime.isEnabled = false

            lblRecordTime.text = convertNSTimeInterval2String(0)

        }

        selectAudioFile()

        if !isRecordMode{

            initPlay()

        }else {

            initRecord()

        }

    }

    @IBAction func btnRecord(_ sender: UIButton) {

        if sender.titleLabel?.text == "Record" {

            audioRecorder.record()

            sender.setTitle("Stop", for: UIControlState())

            progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: timeRecordSelector, userInfo: nil, repeats: true)

        }else {

            audioRecorder.stop()

            progressTimer.invalidate()

            sender.setTitle("Record", for: UIControlState())

            btnPlay.isEnabled = true

            initPlay()

        }

    }

    @objc func updateRecordTime(){

        lblRecordTime.text = convertNSTimeInterval2String(audioRecorder.currentTime)

    }

}



14장 비디오 재생 앱 만들기




//

//  ViewController.swift

//  MoviePlayer

//

//  Created by stayfoolish on 21/10/2018.

//  Copyright © 2018 stayfoolish. All rights reserved.

//


import UIKit

import AVKit


class ViewController: UIViewController {


    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func btnPlayInternalMovie(_ sender: UIButton) {

        // 내부 파일 mp4

        let filePath: String? = Bundle.main.path(forResource: "FastTyping", ofType: "mp4")

        let url = NSURL(fileURLWithPath: filePath!)

        

        playVideo(url: url)

        /*

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

         */

    }

    

    @IBAction func btnPlayExternalMovie(_ sender: UIButton) {

        // 외부 파일 mp4

        let url = NSURL(string: "https://dl.dropboxusercontent.com/s/e38auz050w2mvud/Fireworks.mp4")!

        

        playVideo(url: url)

        /*

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

        */

    }

    private func playVideo(url: NSURL) {

        let playerController = AVPlayerViewController()

        

        let player = AVPlayer(url: url as URL)

        playerController.player = player

        

        self.present(playerController, animated: true){

            player.play()

        }

    }

}



+ Recent posts