HarmonyOS 5.0.0 或以上:实现远程音视频控制 + 数据同步(多端 UI 联动)
📌 场景介绍
在多端协同场景下,常见需求有:
-
手机控制平板播放音视频
-
多端同步播放状态(播放/暂停/进度)
-
一端控制 UI,另一端响应状态联动更新
本篇实现:
-
使用
distributedData
模块做同步通道 -
一端点击播放/暂停,另一端 UI 同步切换状态
-
实现基础远程遥控与 UI 联动
🧱 页面结构
/entry/src/main/ets
└── pages/
└── RemotePlayerControl.ets // 多端联动播放控制页面
🧩 RemotePlayerControl.ets 示例页面
import distributedData from '@ohos.distributedData'
@Entry
@Component
struct RemotePlayerControl {
@State isPlaying: boolean = false
@State syncText: string = '同步状态:--'
private kvStore: distributedData.SingleKvStore | undefined
private key = 'remote_play_status'
async aboutToAppear() {
const context = getContext(this)
const manager = distributedData.createKVManager({
context,
bundleName: 'com.example.harmony',
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
})
this.kvStore = await manager.getSingleKvStore({
storeId: 'media_sync',
options: {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true,
kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
}
})
// 初始化状态
const val = await this.kvStore.get(this.key)
if (val) this.isPlaying = val === 'play'
// 监听远程变化
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (changes) => {
for (let entry of changes.insertEntries) {
if (entry.key === this.key) {
this.isPlaying = entry.value.value === 'play'
this.syncText = `来自远程:${this.isPlaying ? '播放中' : '已暂停'}`
}
}
})
}
private async togglePlayState() {
this.isPlaying = !this.isPlaying
const state = this.isPlaying ? 'play' : 'pause'
await this.kvStore?.put(this.key, state)
this.syncText = `本地设置为:${this.isPlaying ? '播放中' : '已暂停'}`
}
build() {
Column() {
Text("📺 多端播放控制面板").fontSize(22).margin(20)
Button(this.isPlaying ? '⏸️ 暂停' : '▶️ 播放')
.onClick(() => this.togglePlayState())
.fontSize(18)
.margin(10)
Text(this.syncText).fontSize(14).fontColor('#666').margin(10)
Text("💡 同时在多设备运行该页面,即可互相控制播放状态").fontSize(12).fontColor('#999').marginTop(20)
}
.padding(20)
.height('100%')
}
}
✅ 效果说明
-
两台设备都运行此页面
-
一端点击“播放/暂停”按钮
-
另一端页面通过分布式数据监听立即同步状态切换
-
形成远程遥控 + 状态 UI 联动的基础架构
🔧 拓展建议
-
增加播放进度同步(当前时间点)
-
加入音量、倍速、切换视频等指令支持
-
封装为
MediaSyncController
模块支持多页面调用 -
结合
Video
播放组件直接控制远程播放实例