streamer.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. class Streamer {
  2. constructor(containerId, options = {}) {
  3. this.containerId = containerId;
  4. this.options = {
  5. url: 'ws://localhost:8888',
  6. ...options
  7. };
  8. this.player = null;
  9. }
  10. async init() {
  11. try {
  12. // 动态加载UE5像素流的JavaScript库
  13. await this.loadScript('https://cdn.jsdelivr.net/npm/@epicgames-ps/pixel-streaming@latest/dist/player.js');
  14. // 初始化播放器
  15. this.player = new PixelStreaming.Player({
  16. onStateChange: (state) => {
  17. console.log('Streamer state changed:', state);
  18. },
  19. onError: (error) => {
  20. console.error('Streamer error:', error);
  21. }
  22. });
  23. // 连接到UE5服务器
  24. await this.player.connect(this.options.url);
  25. // 将播放器附加到容器
  26. const container = document.getElementById(this.containerId);
  27. if (container) {
  28. this.player.mount(container);
  29. console.log('Streamer initialized successfully');
  30. } else {
  31. throw new Error(`Container with id ${this.containerId} not found`);
  32. }
  33. } catch (error) {
  34. console.error('Failed to initialize streamer:', error);
  35. throw error;
  36. }
  37. }
  38. loadScript(url) {
  39. return new Promise((resolve, reject) => {
  40. const script = document.createElement('script');
  41. script.src = url;
  42. script.onload = resolve;
  43. script.onerror = reject;
  44. document.head.appendChild(script);
  45. });
  46. }
  47. disconnect() {
  48. if (this.player) {
  49. this.player.disconnect();
  50. console.log('Streamer disconnected');
  51. }
  52. }
  53. }
  54. // 将Streamer类挂载到window对象上
  55. window.Streamer = Streamer;