4.7 video 组件

本文详解微信小程序video组件的弹幕功能开发,涵盖预设弹幕自动播放、实时发送弹幕、VideoContext上下文获取与sendDanmu调用;介绍随机十六进制颜色生成、input bind:blur事件处理;强调视频资源必须使用HTTPS外链或云存储ID,禁用本地MP4;并分析基础库版本差异对danmu-btn属性的影响。

一、实验目的

  1. 掌握小程序video视频组件常用属性,实现视频播放。
  2. 理解弹幕机制,学会配置预设弹幕列表danmuList。
  3. 掌握wx.createSelectorQuery()获取VideoContext视频上下文,调用sendDanmu()发送实时弹幕。
  4. 实现随机十六进制颜色函数,让发送的弹幕颜色随机变化。
  5. 了解小程序基础库版本差异:danmu‑btn弹幕开关按钮仅低版本基础库生效,高版本该属性失效。
  6. 掌握 input 输入框bind:blur失去焦点事件获取用户输入内容。

二、实验环境

  • 开发工具:微信开发者工具
  • 项目模式:不使用云服务、不使用模板
  • 渲染引擎:renderer:"webview" webview 渲染模式

三、实验需求分析

基础功能

  1. 页面展示 video 视频播放器,视频播放到指定时间自动播放预设弹幕。
  2. 提供输入框,用户输入文字,点击按钮发送弹幕,弹幕颜色随机生成。
  3. 页面包含橙色外边框,红色页面标题,原生导航栏标题为 video 组件。

作业扩充要求

  1. 切换低版本调试基础库:播放器显示弹幕开关按钮。
  2. 切换高版本调试基础库:弹幕开关按钮消失,弹幕发送功能仍然正常可用。

四、核心知识点梳理

1.video 组件核心属性

表格

属性说明
id组件标识,用于获取视频上下文
src视频资源地址,必须为 https 网络地址或者云文件 ID,不能使用本地项目内 mp4 文件
controls="true"显示播放控件(播放、进度条、全屏)
danmu‑list预设弹幕数组,每个弹幕对象包含text弹幕文字、color弹幕颜色、time弹幕出现时间(单位秒)
enable‑danmu="true"开启弹幕总开关,必须开启弹幕才会显示
danmu‑btn="true"弹幕开关按钮,仅低基础库版本生效,高版本废弃该属性

2.VideoContext 视频上下文

通过wx.createSelectorQuery()查询获取 video 组件上下文对象,调用sendDanmu({text,color})接口,实现向视频发送实时弹幕。

3. 随机十六进制颜色

利用Math.random()生成 0‑255 的数字,使用toString(16)转为十六进制;如果是单字符,前面补0,拼接成#RRGGBB标准颜色格式。

4.input bind:blur 事件

输入框失去焦点才捕获输入内容,保存文本用于后续发送弹幕。

5. 视频资源注意事项

❌禁止直接把 mp4 视频放在小程序项目文件夹,模拟器可以播放,真机直接黑屏。 ✅方案 1:云开发存储上传视频,复制云文件 ID;✅方案 2:外网 HTTPS 视频链接。

五、完整代码实现

1.app.json(全局配置,原生导航栏)

{
  "pages": [
    "pages/index/index"
  ],
  "window": {
    "navigationBarTitleText": "video组件",
    "navigationBarTextStyle": "black",
    "navigationBarBackgroundColor": "#ffffff"
  },
  "style": "v2",
  "renderer": "webview",
  "componentFramework": "glass‑easel",
  "sitemapLocation": "sitemap.json",
  "lazyCodeLoading": "requiredComponents"
}

2.pages/index/index.wxml

<scroll-view class="scrollarea" scroll-y type="list">
  <view class="box">
    <view class="title">华为开发者大会‑2026</view>
    <view class="video-layout">
      <video id="my‑video" src="{{videoPath}}" controls="true" danmu‑list="{{danmuList}}" enable‑danmu="true"></video>
    </view>

    <view class="txt‑style">弹幕内容</view>
    <input type="text" placeholder="在此处输入弹幕内容" bind:blur="inputBlur"/>
    <button type="primary" bind:tap="sendDanmu">发送弹幕</button>
  </view>
</scroll-view>

3.pages/index/index.js

// 获取随机十六进制颜色
function getRandomColor() {
  let rgb = [];
  for(let index = 0; index < 3; index++){
    let color = Math.floor(Math.random() * 256).toString(16);
    color = color.length === 1 ? '0' + color : color;
    rgb.push(color);
  }
  return '#' + rgb.join('');
}

Page({
  data:{
    // 此处替换为你的https视频地址 / 云文件ID
    videoPath:"https://www.w3schools.com/html/mov_bbb.mp4",
    // 预设弹幕:text文字、color颜色、time出现时间(秒)
    danmuList:[
      {
        text:'鸿蒙世界,奔腾不息',
        color:'#ff0000',
        time:1
      },
      {
        text:'HarmonyOS 7',
        color:'#ff00ff',
        time:5
      },
      {
        text:'华为开发者大会2026',
        color:'#00ff00',
        time:10
      },
      {
        text:'携手助力,筑牢金融安全',
        color:'#00ffff',
        time:20
      }
    ]
  },
  onLoad(){
    // 获取VideoContext视频上下文,用于发送弹幕
    const query = wx.createSelectorQuery();
    query.select('#my‑video').context();
    query.exec((res)=>{
      if(res[0]){
        this.videoCtx = res[0].context;
      }
    })
  },
  inputBlur(e){
    // 输入框失去焦点保存输入内容
    this.inputValue = e.detail.value;
  },
  sendDanmu(){
    // 发送自定义弹幕,随机颜色
    this.videoCtx.sendDanmu({
      text: this.inputValue,
      color: getRandomColor()
    })
  }
})

4.pages/index/index.wxss

page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-top: env(safe-area-inset-top);
  box-sizing: border-box;
}

.scrollarea {
  flex: 1;
  overflow-y: hidden;
}

.video-layout {
  display: flex;
  justify-content: center;
}

video {
  width: 95%;
}

.txt-style {
  font-size: large;
  margin-top: 20rpx;
}

input {
  height: 80rpx;
  border-bottom: 2rpx solid blue;
  margin-top: 10rpx;
  margin-bottom: 20rpx;
}

5.app.wxss(全局公共样式)

.box {
  margin: 20rpx;
  padding: 20rpx;
  border: 4rpx solid #FF9500;
}

.title {
  font-size: 40rpx;
  font-weight: bolder;
  text-align: center;
  margin-bottom: 30rpx;
  color: red;
}

6.pages/index/index.json

{}

六、运行效果

  1. 页面顶部原生导航栏标题显示video组件,页面完整展示橙色边框、红色标题。
  2. 视频播放器加载测试视频;视频播放到对应秒数自动弹出预设弹幕。
  3. 在输入框输入文字,点击发送弹幕按钮,视频上弹出随机颜色的弹幕。
  4. 切换调试基础库版本:
    • 低版本(2.32.3):播放器显示弹幕开关按钮。
    • 高版本(3.17.4):弹幕开关按钮消失,发送弹幕功能不受影响。

七、实验踩坑与问题解决

  1. 页面边框、标题看不见,被顶部遮挡 原因:开启navigationStyle:custom自定义导航,页面没有留出状态栏安全高度。 解决:关闭自定义导航栏,使用系统原生导航;css 添加padding‑top: env(safe‑area‑inset‑top)适配手机安全区。
  2. 弹幕按钮 danmu‑btn 不显示 不是代码错误,小程序新版本基础库废弃该属性;切换到低版本调试基础库即可看到弹幕开关。弹幕发送功能高低版本都可用。
  3. 调用 sendDanmu 报错,弹幕发不出去 原因:没有成功获取VideoContext视频上下文,video 标签缺少 id。 解决:video 组件设置id,在onLoad生命周期通过createSelectorQuery获取上下文对象。
  4. 真机视频黑屏无法播放 原因:使用本地项目 mp4 文件或者 http 非加密链接。 解决:视频上传云开发存储拿到云文件 ID,或者使用 https 公开视频地址。
  5. 预设弹幕完全不显示 检查是否开启enable‑danmu="true",确认danmuList数组内 time 时间单位是秒。

八、实验总结

本次实验学习小程序video媒体视频组件,掌握预设弹幕与实时发送弹幕的开发流程。 学会使用wx.createSelectorQuery获取组件上下文,调用组件实例方法。实现随机十六进制颜色生成函数,完成弹幕随机变色效果。 同时认识小程序基础库版本差异性,部分组件属性会随版本迭代废弃。 掌握视频资源的限制规则,理解真机与模拟器行为差异,开发视频小程序时必须使用网络视频资源,不能直接引用本地 mp4 文件。

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值