В настоящее время я это делаю. используя следующее:
- Версия WebRTC: 2.3.3-предварительная версия
- Версия Unity Render Streaming: 3.0.1- предварительный просмотр
- Версия Unity: 2022.3.45f1
Код: Выделить всё
sendvideo.js
import * as Logger from "../../module/logger.js";
export class SendVideo {
constructor(localVideoElement, remoteVideoElement) {
this.localVideo = localVideoElement;
this.remoteVideo = remoteVideoElement;
this.peerConnection = null;
this.dataChannel = null; // Add DataChannel variable
}
async startLocalVideo() {
try {
const videoElement = document.createElement('video');
videoElement.src = '/videos/video.mp4'; // Path to your video file
videoElement.muted = true;
await videoElement.play();
const stream = videoElement.captureStream();
this.localVideo.srcObject = stream;
await this.localVideo.play();
this.initializePeerConnection();
} catch (err) {
Logger.error(`Error starting local video: ${err}`);
}
}
// Set up WebRTC connection and DataChannel
initializePeerConnection() {
this.peerConnection = new RTCPeerConnection();
this.dataChannel = this.peerConnection.createDataChannel("myDataChannel");
this.dataChannel.onopen = () => {
console.log("DataChannel open: Connection established with Unity client");
};
this.dataChannel.onmessage = (event) => {
console.log(`Received message from Unity: ${event.data}`);
};
this.peerConnection.createOffer().then(offer => {
return this.peerConnection.setLocalDescription(offer);
}).then(() => {
console.log("Offer created and sent to Unity client");
}).catch(err => console.error(err));
}
}
Код: Выделить всё
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Unity.WebRTC;
public class ReceiverSample : MonoBehaviour
{
#pragma warning disable 0649
[SerializeField] private Button startButton;
[SerializeField] private Button stopButton;
[SerializeField] private InputField connectionIdInput;
[SerializeField] private RawImage remoteVideoImage;
[SerializeField] private ReceiveVideoViewer receiveVideoViewer;
[SerializeField] private SingleConnection connection;
#pragma warning restore 0649
private RTCDataChannel dataChannel;
private float messageInterval = 2.0f; // Send a message every 2 seconds
void Awake()
{
startButton.onClick.AddListener(OnStart);
stopButton.onClick.AddListener(OnStop);
if (connectionIdInput != null)
connectionIdInput.onValueChanged.AddListener(input => connectionId = input);
receiveVideoViewer.OnUpdateReceiveTexture += texture => remoteVideoImage.texture = texture;
}
private void OnStart()
{
if (string.IsNullOrEmpty(connectionId))
{
connectionId = System.Guid.NewGuid().ToString("N");
connectionIdInput.text = connectionId;
}
connectionIdInput.interactable = false;
// Create the connection
connection.CreateConnection(connectionId, true);
// Subscribe to the DataChannel event (available from the connection object)
connection.OnDataChannel += OnDataChannelReceived;
startButton.gameObject.SetActive(false);
stopButton.gameObject.SetActive(true);
}
private void OnDataChannelReceived(RTCDataChannel channel)
{
dataChannel = channel;
dataChannel.OnOpen += () =>
{
Debug.Log("DataChannel opened. Starting to send messages.");
StartCoroutine(SendHelloWorldMessage());
};
dataChannel.OnClose += () =>
{
Debug.Log("DataChannel closed.");
};
dataChannel.OnMessage += OnMessageReceived;
}
private void OnMessageReceived(byte[] message)
{
string receivedMessage = System.Text.Encoding.UTF8.GetString(message);
Debug.Log($"Message received from WebApp: {receivedMessage}");
}
private IEnumerator SendHelloWorldMessage()
{
while (dataChannel.ReadyState == RTCDataChannelState.Open)
{
dataChannel.Send("Hello World");
Debug.Log("Sent 'Hello World' to JavaScript client");
yield return new WaitForSeconds(messageInterval);
}
}
private void OnStop()
{
StopAllCoroutines();
connection.DeleteConnection(connectionId);
connectionId = String.Empty;
connectionIdInput.text = String.Empty;
connectionIdInput.interactable = true;
startButton.gameObject.SetActive(true);
stopButton.gameObject.SetActive(false);
}
}
Assets\Samples\Unity Render Streaming\3.0.1- Preview\Example\Receiver\ReceiverSample.cs(15,30): ошибка CS0246: не удалось найти тип или имя пространства имен «SingleConnection» (вам не хватает директивы using или ссылки на сборку?)
Assets\Samples \Unity Render Streaming\3.0.1-preview\Example\Receiver\ReceiverSample.cs(15,30): ошибка CS0246: не удалось найти тип или имя пространства имен «SingleConnection» (вам не хватает директивы using или ссылки на сборку ?)
Я хотел бы знать, правильный ли это подход или мой подход к коду с использованием RTCDataChannel подойдет для моего варианта использования, и если да, то как я могу это исправить, чтобы оно работало так, как мне нужно.
Подробнее здесь: https://stackoverflow.com/questions/790 ... ender-stre