上次我在这里问问题时,我表现得像个菜鸟,我希望这次我能走上正轨,清楚自己的问题。
所以我的问题是:我在 PHP 文件中构建了这个播放器,我通过 iframe 将它调用到其他页面以播放视频直播。播放器使用 jwplayer,我想使用 ably库来监控播放器处于播放状态的次数,我希望每个播放器在播放时订阅频道。
这是我启动和订阅的脚本
<!-- ably script to sub on play -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var Ably = require('ably');
var api_key='here we set the api key for the project';
var ably = new Ably.Realtime({key: api_key});
var channel = ably.channels.get('player_status');
channel.subscribe(function(message) {
$(document).ready(function(){
jwplayer().onPlay(function() { alert('playing the video and subscribed'); });
});
});
channel.publish('Video State', 'Playing');
</script>
<!-- Ends here -->
顺便说一句,我应该声明,虽然我可以在一个项目中找到自己的方式,但我对编程仍然很陌生,在这种情况下,其他一切都可以正常工作,只有 ably 功能不起作用。
感谢您提供任何意见,并提前感谢您的宝贵时间。
编辑:这是我试图遵循的一个例子:链接
编辑:在Srushtika Neelakantam女士的帮助下,巧妙的连接和订阅效果很好,现在我必须修改它以更改 jwplayer 状态。
编辑:这段代码现在似乎工作得很好:
<script src="https://cdn.ably.io/lib/ably-1.js"></script>
<script>
var api_key='Enter-Key-Here';
var ably = new Ably.Realtime({key: api_key});
var channel = ably.channels.get('player_status');
channel.subscribe(function(message) {
jwplayer().on('play');
console.log(message.data)//for debug
});
channel.publish('Video State', 'the video is playing');
</script>
<!-- Ends here -->
编辑:但是我的项目经理希望它区分视频的暂停和播放状态,所以我更改了这样的代码,这样它会每 5 秒检查一次视频是否正在播放,如果没有,它会取消订阅频道,重要的是,为此我们需要 channel.detach(); 它不会自动取消订阅(据我所知)
<!-- ably script to sub on play -->
<script src="https://cdn.ably.io/lib/ably-1.js"></script>
<script>
var api_key='----- Enter API key here ----';
var ably = new Ably.Realtime({key: api_key});
var channel = ably.channels.get('player_status');
setInterval(function(){
if (jwplayer().getState() === 'playing'){
channel.subscribe(function(message) {
console.log(message.data)//for debug
});
channel.publish('Video State', 'the video is playing');
}else{
channel.detach();
}
},5000);
</script>
<!-- Ends here -->