dongwan5381 2019-05-07 03:54 采纳率: 100%
浏览 234
已采纳

由golang服务器提供服务时html视频标记无法播放m3u8文件

I have generated the m3u8 file (index.m3u8) from a video and I want to play it on HTML. Basically, I have a golang server which will send the index.m3u8 to the video tag in html5 to play it when http://127.0.0.1:8200/play is called.

my golang file :

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()

}

this is my html file:

<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>

the error i get in console when i go to the url (http://127.0.0.1:8200/play) is

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

To check that the error is not caused by path error, I tried to replace the '{{.}}' in HTML with the full path ('videosource/index.m3u8') and it works perfectly.

Please guide me and show me what's wrong with my code.

Thank you.

  • 写回答

2条回答 默认 最新

  • dre75230 2019-05-07 07:39
    关注

    You have to set your header to the right type. Try something like this:

    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")
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?