本篇简介:
本篇采用Golang的gin框架作为后台,简单设置静态路径和跨域,提供服务,前端采用vue,用vue-video-player进行播放,.m3u8以及.ts采用ffmpeg进行生成。
一、ffmpeg生成.m3u8以及.ts:
ffmpeg.exe -re -i F:\test\mda-jdru2en34rfx8we1.mp4 -c copy -f hls -hls_list_size 0 -bsf:v h264_mp4toannexb F:\test\output\output.m3u8
二、创建文件服务:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //请求头部
var headerKeys []string // 声明请求头keys
for k, _ := range c.Request.Header {
headerKeys = append(headerKeys, k)
}
headerStr := strings.Join(headerKeys, ", ")
if headerStr != "" {
headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
} else {
headerStr = "access-control-allow-origin, access-control-allow-headers"
}
if origin != "" {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
// header的类型
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
// 允许跨域设置 可以返回其他子段
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
c.Set("content-type", "application/json") // 设置返回格式是json
}
if method == "OPTIONS" {
c.JSON(http.StatusOK, "Options Request!")
}
c.Next() // 处理请求
}
}
func main(){
engine := gin.Default()
gin.SetMode(gin.DebugMode)
engine.Use(Cors())
engine.Static("/static","./static/")
engine.Run(":8082")
}
创建static文件夹,将生成好的.m3u8 .ts都放进去
三、vue-video-player播放:
- 首先需要安装vue-video-player:
npm.cmd install vue-video-player videojs-contrib-hls --save
- 代码如下:
<template> <div class="liveView"> <video-player class="vjs-custom-skin" ref="videoPlayer" :options="playerOptions" @ready="onPlayerReadied" @timeupdate="onTimeupdate" :playsinline="playsinline" > </video-player> </div> </template> <script> import { videoPlayer } from "vue-video-player"; import "video.js/dist/video-js.css"; import "vue-video-player/src/custom-theme.css"; import "videojs-contrib-hls"; export default { name: "live", components: { videoPlayer, }, data() { return { initialized: false, currentTech: "", streams: { rtmp: "", hls: "", }, playerOptions: { overNative: true, autoplay: false, controls: true, techOrder: ["html5"], sourceOrder: true, flash: { hls: { withCredentials: false }, }, html5: { hls: { withCredentials: false } }, sources: [ { withCredentials: false, type: "application/x-mpegURL", src: "http://127.0.0.1:8082/static/output.m3u8", }, ], }, }; }, computed: { player() { return this.$refs.videoPlayer.player; }, currentStream() { return this.currentTech === "Flash" ? "RTMP" : "HLS"; }, playsinline() { let ua = navigator.userAgent.toLocaleLowerCase(); // x5内核 if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) { return false; } else { // ios端 return true; } }, }, methods: { onPlayerReadied() { if (!this.initialized) { this.initialized = true; this.currentTech = this.player.techName_; } }, // record current time onTimeupdate(e) { console.log("currentTime", e.cache_.currentTime); }, }, }; </script> <style scoped> .liveView { position: relative; } </style>