Перейти к основному содержимому

RTSP-трансляция

Запустите RTSP-сеанс устройства, выполните сценарий подключения к точке доступа через обратные вызовы и передайте полученный RTSP-адрес совместимому проигрывателю.

Animated workflow

RTSP startup and playback

RTSP startup is a multi-stage device and Wi-Fi workflow. Surface each stage without treating it as final success.

Host app

Configure Stream

Use default RTSP parameters or set documented bitrate, quality, and I-frame values.

SDK + device

Configure Hotspot

Observe hotspot configuration start and completion.

Device

Enter Live Mode

Wait for the device to enter its live-streaming mode.

Device

Wait for Hotspot

The device opens its hotspot before the app can join it.

SDK + iOS

Connect Hotspot

Display the supplied SSID and observe the connection result.

Wi-Fi
Device → app

Receive RTSP URL

Validate and retain the rtsp:// address returned by the SDK.

AIBudsLiveStream

Start Playback

Attach a player view and play the URL as a live VideoSource.

Host app

Session Active

Update active state only after the session-start completion succeeds.

streaming
Terminal callback

Finish and Clean Up

Stop player resources and distinguish user stop from interruption.

The RTSP address and session-start callback are separate events. Retain playback resources until the session finishes or the user stops it.

Предварительные условия​

  • Устройство подключено, готово и соответствует протоколу LiveStreamingAPI.
  • Значение supportsRTSPLiveStreaming равно true.
  • Приложение готово к управляемому SDK сценарию подключения к точке доступа устройства.
  • Для использования показанного ниже RTSP-проигрывателя SDK добавьте AIBudsLiveStream.xcframework.

Справочник API​

Фреймворк​

AIBuds.xcframework, AIBudsFoundation.xcframework и, при необходимости, AIBudsLiveStream.xcframework

Импорт​

Swift
import AIBuds
import AIBudsFoundation
import AIBudsLiveStream

Свойства​

Swift
/// Whether RTSP live streaming is supported
var supportsRTSPLiveStreaming: Bool { get }

Метод экземпляра​

Swift
/// Start RTSP live streaming
/// - Parameters:
///   - params: RTSP stream parameters
///   - configureHotspotStartingHandler: Configure hotspot starting handler
///   - hotspotConfigureCompletionHandler: Hotspot configure completion handler
///   - enterLiveStreamingModeStartingHandler: Enter live streaming mode starting handler
///   - enterLiveStreamingModeCompletedHandler: Enter live streaming mode completed handler
///   - waitingForHotspotOpenHandler: Waiting for hotspot open handler
///   - connectDeviceHotspotStartingHandler: Connect device hotspot starting handler
///   - deviceHotspotConnectCompletionHandler: Device hotspot connect completion handler
///   - rtspAddressReceivedHandler: RTSP address received handler
///   - sessionStartCompletionHandler: Session start completion handler
///   - sessionFinishHandler: Session finish handler
func startRTSPLiveStreaming(
    withParams params: RTSPStreamParams,
    configureHotspotStartingHandler: AIBudsLiveStreamingConfigureHotspotStartingHandler?,
    hotspotConfigureCompletionHandler: AIBudsLiveStreamingHotspotConfigureCompletionHandler?,
    enterLiveStreamingModeStartingHandler: AIBudsEnterLiveStreamingModeStartingHandler?,
    enterLiveStreamingModeCompletedHandler: AIBudsEnterLiveStreamingModeCompletionHandler?,
    waitingForHotspotOpenHandler: AIBudsLiveStreamingStartingToWaitForHotspotOpenHandler?,
    connectDeviceHotspotStartingHandler: AIBudsLiveStreamingConnectDeviceHotspotStartingHandler?,
    deviceHotspotConnectCompletionHandler:
        AIBudsLiveStreamingDeviceHotspotConnectCompletionHandler?,
    rtspAddressReceivedHandler: AIBudsLiveStreamingRtspAddressReceivedHandler?,
    sessionStartCompletionHandler: AIBudsLiveStreamingSessionStartCompletionHandler?,
    sessionFinishHandler: AIBudsLiveStreamingSessionFinishHandler?
)

См. startRTSPLiveStreaming и RTSPStreamParams.

Параметры RTSP​

СвойствоНазначение
bitrateМбит/с. Значение 0 запрашивает настройку устройства по умолчанию.
qualityFactorЗначение 0 запрашивает качество без потерь; большие значения усиливают сжатие.
iFrameIntervalЧисло P/B-кадров перед I-кадром; большие значения усиливают сжатие.

SDK пока не публикует независимые от устройства ненулевые диапазоны этих значений. Используйте RTSPStreamParams.default, если контракт целевого устройства не задаёт поддерживаемые значения.

Примеры использования​

Сохраняйте проигрыватель на протяжении всего сеанса. В примере используются все обратные вызовы сценария, а воспроизведение начинается только после получения корректного RTSP-адреса.

Swift
let player = LiveStreamingPlayer()
player.addVideoView(to: videoContainerView)

guard let streamingDevice = device as? LiveStreamingAPI,
    streamingDevice.supportsRTSPLiveStreaming
else { return }

streamingDevice.startRTSPLiveStreaming(
    withParams: .default,
    configureHotspotStartingHandler: { showStage("Configuring hotspot") },
    hotspotConfigureCompletionHandler: { success, error in
        showStage(
            success
                ? "Hotspot configured"
                : error?.localizedDescription ?? "Hotspot configuration failed")
    },
    enterLiveStreamingModeStartingHandler: { showStage("Entering live-stream mode") },
    enterLiveStreamingModeCompletedHandler: { success, error in
        showStage(
            success
                ? "Live-stream mode entered" : error?.localizedDescription ?? "Mode entry failed")
    },
    waitingForHotspotOpenHandler: { showStage("Waiting for device hotspot") },
    connectDeviceHotspotStartingHandler: { ssid in showStage("Connecting to \(ssid)") },
    deviceHotspotConnectCompletionHandler: { success, error in
        showStage(
            success
                ? "Device hotspot connected"
                : error?.localizedDescription ?? "Hotspot connection failed")
    },
    rtspAddressReceivedHandler: { address in
        guard let url = URL(string: address), url.scheme?.lowercased() == "rtsp" else { return }
        let source = VideoSource(url: url, videoType: .normal)
        source.isLiveStream = true
        player.play(source: source)
    },
    sessionStartCompletionHandler: { success, error in
        setStreamingActive(success)
        if let error { show(error) }
    },
    sessionFinishHandler: { userStopped, error in
        player.stop()
        setStreamingActive(false)
        handleFinish(userStopped: userStopped, error: error)
    }
)

Обработка ошибок​

Рассматривайте настройку точки доступа, вход в режим, подключение, запуск сеанса, ошибку проигрывателя и незапрошенное завершение как отдельные точки отказа. Успешный промежуточный вызов не гарантирует успех последующих этапов или воспроизведения.

Примечания​

  • SDK возвращает RTSP-адрес асинхронно; не формируйте URL устройства самостоятельно.
  • Для RTSP-воспроизведения iPhone должен оставаться подключённым к точке доступа устройства.
  • Demo может ретранслировать полученный RTSP-источник в RTMP через LiveStreamer. Это отдельный жизненный цикл публикации, для которого приложение должно предоставить RTMP-адрес.