【快应用】视频如何根据网络状态播放和暂停

【关键词】

视频,网络,播放与暂停

 

【现象描述】

如今丰富的流媒体时代需要消耗大量的流量,因此需要实现的功能是:

在wifi环境下,可以实现视频的自动播放;切换到移动网络时,需要暂停视频播放,必须用户手动操作才能继续播放。

 

【实现方法】

1、可以通过network.subscribe接口全局监听网络状态的变化,获取网络状态的回调。

2、获取回调信息后,判断当前环境是wifi还是移动网络,从而对video组件进行播放/暂停控制。

详细示例代码如下。

app.ux代码:

<script>

import network from '@system.network';

module.exports = {

onCreate() {

console.info('Application onCreate');

this.listenNetwork();

},

onDestroy() {

console.info('Application onDestroy');

network.unsubscribe();

},

listenNetwork: function () {

console.info("listenNetwork START ");

var that = this

network.subscribe({

callback: function (ret) {

that.data.localeData.currentType = ret.type;

console.info("listenNetwork CALLBACK :" + that.data.localeData.currentType);

},

fail: function (erromsg, errocode) {

console.log('network.subscribe----------' + errocode + ': ' + erromsg)

}

})

},

data: {

localeData: {

currentType: '',

}

}

}

</script>

hello.ux代码:

<template>

<div class="container">

<text class="title">Network Type:{{currentType.currentType}}</text>

<video id="video" style="height: 50%;width: 100%;" src="../Common/demo.mp4"></video>

</div>

</template>

<style>

.container {

flex-direction: column;

justify-content: center;

align-items: center;

}

.title {

font-size: 40px;

}

</style>

<script>
import prompt from '@system.prompt';
module.exports = {
data: {
componentData: {},
currentType: {},
},
onInit() {
this.$page.setTitleBar({
text: 'menu',
textColor: '#ffffff',
backgroundColor: '#007DFF',
backgroundOpacity: 0.5,
menu: true
});
this.currentType = this.$app.$def.data.localeData;
this.$watch('currentType.currentType', 'listenNetType');
},
listenNetType: function (newValue, oldValue) {
console.info("listenNetType newValue= " + newValue + ", oldValue=" + oldValue);
if (newValue === 'wifi') {
this.$element("video").start();
prompt.showToast({
message: 'Wi-Fi, start.',
duration: 3000,
gravity: 'center'
})
} else {
this.$element("video").pause();
prompt.showToast({
message: 'non Wi-Fi, pause.',
duration: 3000,
gravity: 'center'
})
}
},
}
</script>

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

posted @ 2023-04-04 09:16  华为开发者论坛  阅读(212)  评论(0编辑  收藏  举报