[swift] 스위프트에서 미디어 스트리밍 구현하기

미디어 스트리밍은 앱에서 오디오나 비디오를 실시간으로 재생하는 기술입니다. 스위프트에서 미디어 스트리밍을 구현하려면 AVFoundation 프레임워크를 사용할 수 있습니다. 여기에서는 오디오 스트리밍을 예로 들어 구현 방법을 알아보겠습니다.

1. AVPlayer를 이용한 미디어 스트리밍

AVPlayer 클래스를 사용하여 미디어 스트리밍을 구현할 수 있습니다.

import AVFoundation

if let url = URL(string: "your_streaming_url") {
    let player = AVPlayer(url: url)
    player.play()
}

위의 코드에서는 AVPlayer를 생성하고, 스트리밍할 미디어의 URL을 지정한 후 play() 메서드를 호출하여 스트리밍을 시작합니다.

2. 미디어 재생 컨트롤

스트리밍된 미디어를 재생, 일시정지, 정지하는 등의 제어 기능을 추가할 수 있습니다.

// Play the streaming media
player.play()

// Pause the streaming media
player.pause()

// Stop the streaming media
player.replaceCurrentItem(with: nil)

3. 시간 및 상태 관리

AVPlayer를 이용하면 현재 재생 시간, 총 재생 시간, 재생 상태 변화 등을 모니터링할 수 있습니다.

// Get current playback time
let currentTime = player.currentTime()

// Get total duration of the media
if let currentItem = player.currentItem {
    let duration = currentItem.duration
}

// Observing playback state changes
player.addObserver(self, forKeyPath: "status", options: [.new], context: nil)

이제 위의 방법을 활용하여 스위프트 앱에서 미디어 스트리밍을 구현할 수 있게 됩니다.

위의 예제 코드는 오디오 스트리밍을 다루었지만, 비디오 스트리밍도 같은 방법으로 구현할 수 있습니다.

더 자세한 내용은 Apple Developer Documentation를 참고하시기 바랍니다.