HarmonyOS鸿蒙Next中怎么监听web页面里的播放器当web视频播放时候,暂停外部原生播放器,避免出现两个声音
HarmonyOS鸿蒙Next中怎么监听web页面里的播放器当web视频播放时候,暂停外部原生播放器,避免出现两个声音
4 回复
给web组件添加一个权限mediaPlayGestureAccess(false) web自动播放
代码如下:
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({
src: "www.example.com",
controller: this.controller
}).mediaPlayGestureAccess(false)
}
}
}
更多关于HarmonyOS鸿蒙Next中怎么监听web页面里的播放器当web视频播放时候,暂停外部原生播放器,避免出现两个声音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
太顶了,折磨我好几天了,
在HarmonyOS Next中监听Web页面播放器状态,可通过Web组件onAudioStateChange回调实现。当检测到Web视频开始播放时,调用原生AVPlayer的pause()方法暂停外部播放器。关键代码示例:
webViewController.onAudioStateChange((isPlaying: boolean) => {
if (isPlaying) {
avPlayer.pause();
}
});
需同时配置Web组件启用音频状态监听:
webComponent.setAudioAllowed(true);
该方案直接通过鸿蒙Web组件API实现,不涉及Java/C。
在HarmonyOS Next中,可以通过Web组件与原生代码的交互来实现这个需求。以下是实现方案:
- 使用Web组件的JavaScript注入功能,在Web页面中注入监听代码:
// 在ArkTS中设置Web组件
webController.javaScriptProxy({
object: {
// 注入原生方法供网页调用
notifyVideoPlay: () => {
// 暂停原生播放器
nativePlayer.pause();
},
notifyVideoPause: () => {
// 恢复原生播放器逻辑
}
},
name: 'HarmonyProxy',
methodList: ['notifyVideoPlay', 'notifyVideoPause']
});
- 在Web页面中添加视频播放监听:
// 网页中的JavaScript代码
const videoElements = document.getElementsByTagName('video');
Array.from(videoElements).forEach(video => {
video.addEventListener('play', () => {
// 调用HarmonyOS原生方法
window.HarmonyProxy.notifyVideoPlay();
});
video.addEventListener('pause', () => {
window.HarmonyProxy.notifyVideoPause();
});
});
- 对于动态加载的内容,可以使用MutationObserver监听DOM变化:
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.addedNodes.length) {
// 检查新增节点中是否有video元素
const videos = mutation.target.getElementsByTagName('video');
Array.from(videos).forEach(v => {
v.addEventListener('play', () => window.HarmonyProxy.notifyVideoPlay());
v.addEventListener('pause', () => window.HarmonyProxy.notifyVideoPause());
});
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
这个方案通过Web与原生交互,在检测到网页视频播放时暂停原生播放器,能有效避免声音冲突问题。