iOS/Swift 어플 따라하기

[Swift] 뮤직 플레이어 코드 / 싱글 톤 객체 만들기

Chafle 2022. 3. 22. 18:38
반응형

 

싱글톤 객체 만들기

싱글 톤 객체는

플레이어를 매번 생성하는 것이 아니고 하나만 만들고 객체로 불러서 사용 하는 것입니다.

 

static let shared = SimplePlayer() 

 let simplePlayer = SimplePlayer.shared //돌려쓰는 플레이어를 가져와서 사용하겠다는 의미입니다.

여기서의 SimplePlayer()는 Class를 만들어

플레이어 현재 진행 시간, 총 길이, 곡정보의 정보를 담고 있습니다.


반응형

 

SimplePlayer에 현재 시간, 곡의 총 길이, 곡 정보 넣기

 

※  private let player = AVPlayer()

곡의 현재 진행 시간 불러오기

var currentTime: Double {

        return player.currentItem?.currentTime().seconds ?? 0

    }

   // 현재 플레이어에서 재생하는 CurrentItem이 있을 수 있고 없을 수 있는데 있다면, 현재시간을 가져오고 CMTIME타입인데 Double타입으로 호출하고 없으면 0반환 해라는 의미입니다.

 

곡의 총 길이 불러오기

var totalDurationTime: Double {

        return player.currentItem?.duration.seconds ?? 0

    }

      // 현재 아이템에 전체 곡 길이: Duration 전체 길이 메서드 -> 더블로 바꾸는 메서드 없으면 0 반환하라는 의미입니다.

 

current item추가(곡에 대한 정보들)

var currentItem: AVPlayerItem? {

        return player.currentItem

}

실제로 player.currentItem을 반환하지 않으면 updateTrackInfo로 곡정보를 넘겨도

빌드는 성공하지만

시뮬레이터를 돌리면 홈에서 곡 정보를 눌렀을 때 플레이어에 '곡 정보'들이 넘어오지 않습니다.

 

딥스터디 부분( 넘어가셔도 좋습니다.)
현재 재생중..? 

var isPlaying: Bool {

        return player.isPlaying

    }

 


extension AVPlayer {

    var isPlaying: Bool {

        guard self.currentItem != nil else { return false }

        return self.rate != 0

    }

}

 


곡을 정지, 재생, 탐색, 곡을 갈아치우기?(다음곡 재생)

private let player = AVPlayer()

//player에 AVPlyaer()를 할당 해줍니다.

 

init() { }

    

정지

    func pause() {

        player.pause()

    }

재생

func play() {

        player.play()

    }

탐색

    func seek(to time:CMTime) {

        player.seek(to: time)

    }

곡 교체

    func replaceCurrentItem(with item: AVPlayerItem?) {

        player.replaceCurrentItem(with: item)

    }

 

 


 

반응형