간단한 오디오 플레이어 샘플예제이다.


오디오로 사용할 mp3 파일을 프로젝트안에 드래그앤 드랍하여 복사한다.


Main.storyboard 에 시작버튼 정지버튼 그리고 볼륨을 조절할 수 있는 컨트롤러 오브젝트를 넣고 ViewController.swift  파일에 outlet, action 등을 연결한다.





아래는 ViewController.swift 파일의 소스 전체이다.


import UIKit

import AVFoundation


class ViewController: UIViewController, AVAudioPlayerDelegate {

    

    @IBOutlet weak var volumeControl: UISlider!

    var audioPlayer : AVAudioPlayer?


    @IBAction func playAudio(sender: AnyObject) {

        if let player = audioPlayer {

            player.play()

        }

    }

    

    @IBAction func stopAudio(sender: AnyObject) {

        if let player = audioPlayer {

            player.stop()

        }

    }

    

    @IBAction func adjustVolume(sender: AnyObject) {

        if audioPlayer != nil {

            audioPlayer?.volume = volumeControl.value

        }

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

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

        

        let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("Moderato", ofType: "mp3")!)

        do {

            try audioPlayer = AVAudioPlayer(contentsOfURL: url)

            audioPlayer?.delegate = self

            audioPlayer?.prepareToPlay()

        } catch let error as NSError {

            print("audioPlayer error \(error.localizedDescription)")

        }

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

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

        

    }

    

    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {

        

    }

    

    func audioPlayerBeginInterruption(player: AVAudioPlayer) {

        

    }

    

    func audioPlayerEndInterruption(player: AVAudioPlayer) {

        

    }



}


+ Recent posts