iOS, AVFoundation_AVPlayer()

iDOยท2021๋…„ 10์›” 17์ผ
0

iOS

๋ชฉ๋ก ๋ณด๊ธฐ
1/8
post-thumbnail

๐Ÿง Player๋ฅผ ๋งŒ๋“ค ์ผ์ด ์ƒ๊ฒจ AVFoundation์„ ์ด์šฉํ•ด Player๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๊ธฐ์ดˆ์ ์ธ ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค.

Step1

๋‹น์—ฐํžˆ ์ฒ˜์Œ์—๋Š” AVFoundation์„ import ํ•ด์ค˜์•ผํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ Player.swift

import AVFoundation
Step2

Player๋ผ๋Š” Class๋ฅผ ์ƒ์„ฑํ•ด์ฃผ๊ณ  ์ƒ์„ฑํ•œ ํด๋ž˜์Šค ๋‚ด์— AVPlayer ์ธ์Šคํ„ด์Šค๋ฅผ ์„ ์–ธํ•ด์ค๋‹ˆ๋‹ค.

๐Ÿ Player.swift

import AVFoundation

class Player {
    private let player = AVPlayer()
}
Step3

AVPlayer์—์„œ ํ•„์š”ํ•œ ๋ฉ”์†Œ๋“œ๋“ค์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ €๋Š” item, ์žฌ์ƒ์‹œ๊ฐ„, ์ด์‹œ๊ฐ„, ์žฌ์ƒ, ์ผ์‹œ์ •์ง€ ์ด๋ ‡๊ฒŒ ์šฐ์„  ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ Player.swift

import AVFoundation

class Player {
    private let player = AVPlayer()
    
    var currentItem: AVPlayerItem? {
        return player.currentItem
    }
    
     func replaceCurrentItem(with item: AVPlayerItem?) {
        player.replaceCurrentItem(with: item)
    }
    
    var currentTime: Double {
        return player.currentItem?.currentTime().seconds ?? 0
    }
    
    var durationSeconds: Double {
        return player.currentItem?.duration.seconds ?? 0
    }
    
    func pause() {
        player.pause()
    }
    
    func play() {
        player.play()
    }
    
    func seek(to time:CMTime) {
        player.seek(to: time)
    }
    
    func periodicTimeObserver(interval: CMTime, queue: DispatchQueue, using: @escaping (CMTime) -> Void) {
        player.addPeriodicTimeObserver(forInterval: interval, queue: queue, using: using)
    }
}
Step3 +

์ €๋Š” ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์„ ์ ์šฉ์‹œ์ผฐ์Šต๋‹ˆ๋‹ค.
ํ˜„์žฌ ์žฌ์ƒ์ค‘์ธ ์ƒํƒœ๋ฅผ ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์žˆ์–ด์„œ extension AVPlayer๋ฅผ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค

๐Ÿ Player.swift

class Player {
    static let shared = Player()
    init() { }
    ...
    var isPlaying: Bool {
        return player.isPlaying
    }
}

extension AVPlayer {
    var isPlaying: Bool {
        guard self.currentItem != nil else { return false }
        return self.rate != 0
    }
}
Step4

๋ทฐ์— ์ ์šฉํ•ฉ์‹œ๋‹ค.

๐Ÿ ViewController.swift

import UIKit

class PlayerViewController: UIViewController {
    let player = Player.shared
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.player.replaceCurrentItem(with: ...) // ํ•„์š”ํ•œ ๋ฐฉ์‹์œผ๋กœ AVPlayerItem()์„ ๋ถˆ๋Ÿฌ์™€์ฃผ์„ธ์š”. ์ €๋Š” ์ฃผ๋กœ url๋กœ ์Œ์›ํŒŒ์ผ์„ ๋ถˆ์–ด์™”์Šต๋‹ˆ๋‹ค.
    }
    
    //MARK: ํ•„์š”ํ•œ ๋ฒ„ํŠผ Action์„ ์ถ”๊ฐ€ํ•ด์„œ ์ ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค!
}

๐Ÿง(์•„๋ž˜ ์ฐธ๊ณ ๋‚ด์šฉ์„ ํ†ตํ•ด ๋” ์ž์„ธํ•œ ์ •๋ณด๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!)
Apple Developer Documentation

profile
์ด๊ณณ์€ ์ €๋ฅผ ์œ„ํ•œ iOS ์„ค๋ช…์„œ์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€