iOS 앱에서 오디오와 비디오를 재생하는 방법을 이해하는 것은 매우 중요합니다. 요즘 거의 모든 애플리케이션이 오디오나 비디오 기능을 포함하고 있기 때문입니다. 게임 앱부터 소셜 미디어, 음악 플레이어에 이르기까지 다양한 분야에서 멀티미디어 재생은 필수적인 기능이 되었습니다.
이 글에서는 Swift를 사용해 오디오 파일과 비디오 파일을 재생하는 방법을 단계별로 살펴보겠습니다.
프로젝트 준비하기
1단계 – Xcode를 실행하고 New Project → Single View Application을 선택한 후, 프로젝트 이름을 "AudioVideo"로 지정합니다.
2단계 – Main.storyboard를 열고 버튼 세 개를 추가한 뒤 아래 이미지와 같이 이름을 지정합니다.

3단계 – 세 개의 버튼에 @IBOutlet을 연결하고 각각 stop, playButton, videoButton으로 이름을 지정합니다. 이름 그대로 각각 소리를 멈추고, 소리를 재생하고, 비디오를 재생하는 역할을 담당하게 됩니다.
AVFoundation 프레임워크 이해하기
4단계 – Apple에서 제공하는 AVFoundation 프레임워크를 사용합니다. AVFoundation은 캡처, 처리, 합성, 제어, 가져오기, 내보내기 등 Apple 플랫폼에서 오디오비주얼 미디어와 관련된 광범위한 작업을 수행할 수 있는 네 가지 주요 기술 영역을 통합한 프레임워크입니다.
5단계 – 프로젝트 설정에서 Build Phases로 이동하여 아래 이미지와 같이 AVFoundation 프레임워크를 추가합니다.

6단계 – 프로젝트 디렉터리에 재생하려는 mp3/오디오 파일을 추가합니다.
오디오 재생 구현하기
7단계 – ViewController.swift 상단에 프레임워크를 임포트합니다.
import AVFoundation
8단계 – AVAudioPlayer 객체를 생성합니다.
var avPlayer = AVAudioPlayer()
9단계 – 재생 버튼의 IBAction에 아래 코드를 작성합니다. Bundle에서 mp3 파일의 URL을 찾아 AVAudioPlayer로 로드한 뒤 재생하는 방식입니다.
@IBAction func playButton(_ sender: Any) {
guard let url = Bundle.main.url(forResource: "sample", withExtension: "mp3")
else {
return
}
do {
avPlayer = try AVAudioPlayer(contentsOf: url)
avPlayer.play()
}
catch {
}
}10단계 – 정지 버튼의 IBAction에는 다음 한 줄만 작성하면 됩니다.
@IBAction func stop(_ sender: Any) {
avPlayer.stop()
}비디오 재생 구현하기
11단계 – 비디오 버튼에는 아래 코드를 작성합니다. AVPlayer와 AVPlayerLayer를 활용해 화면 전체에 비디오 레이어를 추가하고 재생하는 구조입니다.
@IBAction func videoButton(_ sender: Any) {
let path = Bundle.main.path(forResource: "one", ofType: "mp4")
let videoUrl = URL(fileURLWithPath: path!)
let player = AVPlayer(url: videoUrl as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}앱을 실행하면 오디오와 비디오가 정상적으로 재생되는 것을 확인할 수 있습니다.
전체 예제 코드
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func stop(_ sender: Any) {
avPlayer.stop()
}
@IBAction func playButton(_ sender: Any) {
UIScreen.main.brightness = 0.6
guard let url = Bundle.main.url(forResource: "sample", withExtension: "mp3")
else {
return
}
do {
avPlayer = try AVAudioPlayer(contentsOf: url)
avPlayer.play()
}
catch {
}
}
@IBAction func videoButton(_ sender: Any) {
let path = Bundle.main.path(forResource: "one", ofType: "mp4")
let videoUrl = URL(fileURLWithPath: path!)
let player = AVPlayer(url: videoUrl as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}참고로 위 전체 코드의 playButton 메서드에는 UIScreen.main.brightness = 0.6이라는 코드가 포함되어 있는데, 이는 재생 시 화면 밝기를 조절하는 예시입니다. 필요하지 않다면 제거해도 무방합니다.