javascript - 仅使用控件将音频从 html5 javascript 流式传输到 chromecast

标签 javascript html chromecast google-cast

仅通过浏览器将带有控件的音频从 html5 javascript 流式传输到 chromecast。 我只需要使用我的电脑将音频流式传输到 googlechromecast。我正在使用 Chrome 浏览器。我需要做的就是仅使用我的控件甚至我正在播放的歌曲的屏幕图像来流式传输音频。目前我无法实现这一目标。

var applicationID = 'some id';
var namespace = 'some namespace';
var session = null;

/**
 * Call initialization for Cast
 */
if (!chrome.cast || !chrome.cast.isAvailable) {
  setTimeout(initializeCastApi, 1000);
}

/**
 * initialization
 */
function initializeCastApi() {
  var sessionRequest = new chrome.cast.SessionRequest(applicationID);
  var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
    sessionListener,
    receiverListener);

  chrome.cast.initialize(apiConfig, onInitSuccess, onError);
};

/**
 * initialization success callback
 */
function onInitSuccess() {
  appendMessage("onInitSuccess");
}

/**
 * initialization error callback
 */
function onError(message) {
  appendMessage("onError: "+JSON.stringify(message));
}

/**
 * generic success callback
 */
function onSuccess(message) {
  appendMessage("onSuccess: "+message);
}

/**
 * callback on success for stopping app
 */
function onStopAppSuccess() {
  appendMessage('onStopAppSuccess');
}

/**
 * session listener during initialization
 */
function sessionListener(e) {
  appendMessage('New session ID:' + e.sessionId);
  session = e;
  session.addUpdateListener(sessionUpdateListener);
  session.addMessageListener(namespace, receiverMessage);
}

/**
 * listener for session updates
 */
function sessionUpdateListener(isAlive) {
  var message = isAlive ? 'Session Updated' : 'Session Removed';
  message += ': ' + session.sessionId;
  appendMessage(message);
  if (!isAlive) {
    session = null;
  }
};

/**
 * utility function to log messages from the receiver
 * @param {string} namespace The namespace of the message
 * @param {string} message A message string
 */
function receiverMessage(namespace, message) {
  appendMessage("receiverMessage: "+namespace+", "+message);
};

/**
 * receiver listener during initialization
 */
function receiverListener(e) {
  if( e === 'available' ) {
    appendMessage("receiver found");
  }
  else {
    appendMessage("receiver list empty");
  }
}

/**
 * stop app/session
 */
function stopApp() {
  session.stop(onStopAppSuccess, onError);
}

/**
 * send a message to the receiver using the custom namespace
 * receiver CastMessageBus message handler will be invoked
 * @param {string} message A message string
 */
function sendMessage(message) {
  if (session!=null) {
    session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError);
  }
  else {
    chrome.cast.requestSession(function(e) {
        session = e;
        session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError);
      }, onError);
  }
}

/**
 * append message to debug message window
 * @param {string} message A message string
 */
function appendMessage(message) {
  console.log(message);
  var dw = document.getElementById("debugmessage");
  dw.innerHTML += '\n' + JSON.stringify(message);
};

/**
 * utility function to handle text typed in by user in the input field
 */
function update() {
  sendMessage(document.getElementById("input").value);
}

/**
 * handler for the transcribed text from the speech input
 * @param {string} words A transcibed speech string
 */
function transcribe(words) {
  sendMessage(words);
}

请帮忙。请告诉我是否有办法实现这一目标。

添加另一个代码,我可以对其进行修改以满足我的需求。但问题是它只能连接。选项卡显示已连接并正在播放,但我听不到 chromecast(电视)的音频。请帮助我解决有关音频流的问题。

    'use strict';
    var DEVICE_STATE = {
      'IDLE' : 0,
      'ACTIVE' : 1,
      'WARNING' : 2,
      'ERROR' : 3,
    };

    /**
     * Constants of states for CastPlayer
     **/
    var PLAYER_STATE = {
      'IDLE' : 'IDLE',
      'LOADING' : 'LOADING',
      'LOADED' : 'LOADED',
      'PLAYING' : 'PLAYING',
      'PAUSED' : 'PAUSED',
      'STOPPED' : 'STOPPED',
      'SEEKING' : 'SEEKING',
      'ERROR' : 'ERROR'
    };

  var streamCaster = function(ele,url)
  {
    this.playUrl = url;
    this.castPlayer =null;
    this.receiverAvailable = null;
    this.init(ele);
    this.initCastPlayer();
    console.log("Playing URL "+this.playUrl);
  }


  streamCaster.prototype.init = function(ele)
  {
    console.log("Init Player");
    this.castPlayer = document.getElementById(ele);
    this.castPlayer.addEventListener('loadeddata', this.onMediaLoadedLocally.bind(this));
  }

  streamCaster.prototype.onMediaLoadedLocally = function()
  {
    console.log("Playing Audio");
    this.castPlayer.play();

  };

  streamCaster.prototype.initCastPlayer = function() {
    console.log("Init Chrome-Cast");
    if (!chrome.cast || !chrome.cast.isAvailable) {
      console.log("No Support For Chrome Cast..Re Trying");
      setTimeout(this.initCastPlayer.bind(this), 1000);
      return;
    }
      var applicationID = 'Yr ID';
      // auto join policy can be one of the following three
      var autoJoinPolicy = chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED;
      //var autoJoinPolicy = chrome.cast.AutoJoinPolicy.PAGE_SCOPED;
      //var autoJoinPolicy = chrome.cast.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED;
      // request session
        var sessionRequest = new chrome.cast.SessionRequest(applicationID);
        var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
        this.sessionListener.bind(this),
        this.receiverListener.bind(this),
        autoJoinPolicy);
        chrome.cast.initialize(apiConfig, this.onInitSuccess.bind(this), this.onError.bind(this));
  }

  streamCaster.prototype.onError = function() {
    console.log("error");
  };

  streamCaster.prototype.onInitSuccess = function() {
    console.log("init success");
    this.startChromeCast();
  };

  streamCaster.prototype.sessionListener = function(e) {
    this.session = e;
    if( this.session )
    {
      if( this.session.media[0] )
      {
        this.onMediaDiscovered('activeSession', this.session.media[0]);
        this.syncCurrentMedia(this.session.media[0].media.contentId);
        this.selectMediaUpdateUI(this.currentMediaIndex);
      }
      else
      {
        this.loadMedia(this.currentMediaIndex);
      }
      this.session.addUpdateListener(this.sessionUpdateListener.bind(this));
    }
  }

  streamCaster.prototype.loadMedia = function(mediaIndex) {
    if (!this.session)
    {
      console.log("no session");
      return;
    }
    //console.log("loading..." + this.mediaContents[mediaIndex]['title']);
    var mediaInfo = new chrome.cast.media.MediaInfo(this.playUrl);

    mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata();
    mediaInfo.metadata.metadataType = chrome.cast.media.MetadataType.GENERIC;
    mediaInfo.contentType = 'audio/mp3';

    mediaInfo.metadata.title = "Castlevania Symphony Of The Night";
  //  mediaInfo.metadata.images = [{'url': MEDIA_SOURCE_ROOT + this.mediaContents[mediaIndex]['thumb']}];

    var request = new chrome.cast.media.LoadRequest(mediaInfo);
    request.autoplay = this.autoplay;
      request.currentTime = this.castPlayer.currentTime;
    //   this.castPlayer.pause();
    //   this.castPlayer = PLAYER_STATE.STOPPED;
    //
    //
    // this.castPlayerState = PLAYER_STATE.LOADING;
    this.session.loadMedia(request,
      this.onMediaDiscovered.bind(this, 'loadMedia'),
      this.onLoadMediaError.bind(this));

  };

  streamCaster.prototype.onMediaDiscovered = function(how, mediaSession) {
    this.currentMediaDuration =-1;
    this.currentMediaSession = mediaSession;
    this.currentMediaSession.addUpdateListener(function()
    {
      console.log("binding");
    });
  };
  streamCaster.prototype.onLoadMediaError = function(e) {
    console.log("media error");
  };



  streamCaster.prototype.sessionUpdateListener = function(isAlive) {
    if (!isAlive)
    {
      this.session = null;
      this.deviceState = DEVICE_STATE.IDLE;
      this.castPlayerState = PLAYER_STATE.IDLE;
      this.currentMediaSession = null;

      var online = navigator.onLine;
      if( online == true )
      {
        // continue to play media locally
        this.playMediaLocally();
      }
    }
  };

  streamCaster.prototype.playMediaLocally = function() {

      this.castPlayer.load();
      this.castPlayer.play();
  };


  streamCaster.prototype.receiverListener = function(e) {
    if( e === 'available' ) {
      this.receiverAvailable = true;
      console.log("receiver found");
    }
    else {
      console.log("receiver list empty");
    }
  }

  streamCaster.prototype.startChromeCast = function() {
    console.log("launching app...");
    chrome.cast.requestSession(
      this.sessionListener.bind(this),
      this.onLaunchError.bind(this));


    if( this.timer ) {
      clearInterval(this.timer);
    }
  };

  streamCaster.prototype.onLaunchError = function() {
    console.log("launch error");
  };

最佳答案

我围绕 chromecast SDK 创建了一个简单的 JavaScript 包装器:
https://github.com/fenny/castjs

var device = new Castjs()
device.on('available', function() {
    cc.cast('https://example.com/music.mp3', {
        poster:      'https://example.com/album.jpg',
        title:       'Artist - Song',
        description: 'Album'
    })
})

这个包装器还有更多选项,您可以查看上面 github 链接上的文档

祝你好运!

关于javascript - 仅使用控件将音频从 html5 javascript 流式传输到 chromecast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33757274/

相关文章:

javascript - 使用复选框和 Angular 将 true/false 值设置为 localStorage

javascript - 为什么我的 mod_perl 应用程序中的 UTF8 数据在 Web 浏览器中仍然出现乱码?

c# - 如何在 blazor 项目中使用 C# 绑定(bind)制作 HTML 文本多行?

html - 如何在尽可能小的框中获得居中文本

html - 如何为我们的网站制作盲文界面

google-chrome - 如何检测 Chrome 中是否安装了 Google Cast 扩展程序?

javascript - AngularJS 指令内的编译指令

javascript - 如何将动态 ID 传递给 JQuery 中的函数

android - Chromecast 发送器应用程序未检测到断开连接/重新连接

chromecast - 断开和重新连接客户端到接收器 session