由golang服务器提供服务时html视频标签不播放m3u8文件

标签 html go video http-live-streaming m3u8

我已经从视频生成了 m3u8 文件 (index.m3u8),我想在 HTML 上播放它。 基本上,我有一个 golang 服务器,它将 index.m3u8 发送到 html5 中的视频标签,以便在 http://127.0.0.1:8200/play 时播放它。被称为。

我的 golang 文件:

package main

import(
"fmt"
"net/http"
"html/template"
)


func serveHandler(w http.ResponseWriter, r *http.Request){

    tmpl := template.Must(template.ParseFiles("index.html"))

    tmpl.Execute(w, "videosource/index.m3u8")

}


func main(){

fmt.Println("begin listening to port 8200")

server := http.Server{
    Addr: "127.0.0.1:8200",
}
http.HandleFunc("/play",serveHandler)
server.ListenAndServe()

}

这是我的 html 文件:

<html>
  <body>
<script src="https://cdn.jsdelivr.net/npm/hls.js@canary"></script>
<video id="video" controls autoplay></video>
<script>
if(Hls.isSupported())
{
    var video = document.getElementById('video');
    var hls = new Hls();
    hls.loadSource('{{.}}');
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function()
    {
        video.play();
    });
}
else if (video.canPlayType('application/vnd.apple.mpegurl'))
{
    video.src = '{{.}}';
    video.addEventListener('canplay',function()
    {
        video.play();
    });
}
</script>

当我转到 url ( http://127.0.0.1:8200/play) 时,我在控制台中遇到的错误是

videosource/index.m3u8:1 Failed to load resource: the server responded with a status of 404 (Not Found)

为了检查错误不是由路径错误引起的,我尝试用完整路径('videosource/index.m3u8')替换 HTML 中的 '{{.}}' 和它完美地工作。

请指导我并告诉我我的代码有什么问题。

谢谢。

最佳答案

您必须将 header 设置为正确的类型。 尝试这样的事情:

func serveHandler(w http.ResponseWriter, r *http.Request){
  w.Header().Set("Content-Type", "application/x-mpegURL")

  tmpl := template.Must(template.ParseFiles("index.html"))
  tmpl.Execute(w, "videosource/index.m3u8")

}

关于由golang服务器提供服务时html视频标签不播放m3u8文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015322/

相关文章:

html - 如何为表格行设置边框和填充?

javascript - 在 angularjs 形式中使用 ng-model 的边缘情况

javascript - 在 Angular ng-switch 中使用 html 模板

ios - SWIFT:MediaPlayer - 完成按钮不执行任何操作

video - 你能控制在 Quartz Composer 中播放视频剪辑的速度吗?

html - 如何使 div 响应的背景图像?

mongodb - 从请求中序列化一个表单并放入 mongo

go - 如何通过标准输入将 []byte 传递给外部 exiftool?

去 fmt.Scan into Array

html - (webrtc)setRemoteDescription对启动器不起作用