electron 静态本地视频加载问题解决方法

1,114 阅读1分钟

1.先说一下项目构建工具,electron-vue几年没更新了,不建议使用坑太多,

vue-cli-plugin-electron-builder,一直再维护
1.先用vue-cli 创建vue项目
2.再vue项目里面运行vue add electron-builder

image.png 2.把视频放在pulbic目录里,图片可以新建static放里面,然后打开background.js

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
  // Add this here:新增视频处理方法
  registerLocalVideoProtocol()

// And this anywhere:
  function registerLocalVideoProtocol () {
    protocol.registerFileProtocol('local-video', (request, callback) => {
      const url = request.url.replace(/^local-video:///, '')
      const path=require('path')
      // Decode URL to prevent errors when loading filenames with UTF-8 chars or chars like "#"
      const decodedUrl = decodeURI(url) // Needed in case URL contains spaces
      try {
        // eslint-disable-next-line no-undef
        return callback(path.join(__static, decodedUrl))//这步是路径指向public目录
      } catch (error) {
        console.error(
            'ERROR: registerLocalVideoProtocol: Could not get file path:',
            error
        )
      }
    })
  }
})

__static会自动指向public目录,如下图源码文件所示

image.png 3.然后在组件中调用

<video src="local-video://ae.mp4" autoplay loop></video>
local-video://

local-video://,这个就直接指向public目录,打包后静态视频就能正常加载