【问题标题】:How to implement HLS video service with Vue3.js single page application如何用Vue3.js单页应用实现HLS视频服务
【发布时间】:2022-12-04 23:47:54
【问题描述】:
我正在使用 Vue.js 创建视频流平台。但是,我遇到了无法解决的问题。那就是当我们使用 Vue.js 之类的 SPA 时,javascript 在浏览器上运行,因此我们必须从服务器端 API 接收段文件。如果我使用 MPA,我所要做的就是指定 .m3u8 文件的位置。
我正在为 Node.js 使用 express。
我的问题是如何创建将 .m3u8 文件和分段 .ts 文件发送到客户端 Vue.js 的 API。现在,所有 .m3u8 和 .ts 段文件都在服务器端,所以我想知道如何使用 SPA 和 node.js 从服务器端 API 访问或接收数据。
【问题讨论】:
标签:
node.js
vue.js
http-live-streaming
hls.js
【解决方案1】:
要使用 Express 从 Node.js 服务器提供 .m3u8 和 .ts 文件,您可以使用 express.static 中间件函数从服务器上的目录提供文件。此中间件函数将包含文件的目录的路径作为其唯一参数。
下面是一个示例,说明如何使用 express.static 中间件从名为 public 的目录中提供 .m3u8 和 .ts 文件:
const express = require('express')
const app = express()
// Serve the files in the "public" directory
app.use(express.static('public'))
// Start the server
const port = 3000
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
})
设置服务器以提供文件后,您可以通过使用获取 API 或 Axios 等库向服务器发出 HTTP 请求来访问 Vue.js 应用程序中的 .m3u8 文件和 .ts 段文件。例如,您可以使用以下代码请求 .m3u8 文件:
// Make a request for the .m3u8 file
fetch('/path/to/file.m3u8')
.then(response => response.text())
.then(data => {
// Use the data here
})
.catch(error => {
// Handle the error here
})
然后,您可以使用请求返回的数据,使用 HLS.js 等播放器库加载视频。关于在 Vue.js 中使用 HLS.js 的更多信息,您可以查看官方文档here。