【问题标题】:html video tag not playing m3u8 file when serve by golang servergolang服务器提供时html视频标签不播放m3u8文件
【发布时间】:2019-09-24 16:29:10
【问题描述】:

我已经从一个视频中生成了 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)

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

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

谢谢。

【问题讨论】:

    标签: html go video http-live-streaming m3u8


    【解决方案1】:

    您必须将标题设置为正确的类型。 试试这样的:

    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")
    
    }
    

    【讨论】:

    • 感谢您的回答。有用。但是,还有另一个错误弹出 hls.js@latest:1 Access to XMLHttpRequest at 'file:///home/jetherng/go/src/stream/%7B%7B.%7D%7D' from origin 'null'已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。对此有任何想法吗?
    • 您必须在您的网络服务器上启用跨源 (CORS)。看这里flaviocopes.com/golang-enable-cors
    猜你喜欢
    • 2013-11-15
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多