如何为 html5 视频标签流式传输视频文件

How to stream a video file for html5 video tag

我想知道在 Go 中流式传输视频文件(mpg4/avi - 或任何其他格式)的最佳方式是什么。可能,我希望能够使用一个简单的标签播放它。

我试过用这段代码播放著名的 Big Buck Bunny 文件:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}

但是当在我的浏览器中加载 html 页面时,没有播放任何内容,实际上只触发了一个 http 请求,并且只有一个包含 206 部分内容的响应被发送到页面。

html页面正文中包含以下代码:

<video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>

谢谢!

你的 go 代码看起来不错,让我认为这可能是你的视频有问题。 html5 通常不支持 avi,有关 html5.

的 containers/codecs 的更多详细信息,请参阅 here

我会尝试使用已知的工作视频。例如:https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4

甚至可以简化您的代码并只使用 http.ServeFile,尽管视频服务的重要部分(范围请求)无论如何都在 ServeContent 中。

我只是 运行 你的代码,并且在 Chrome 的最新版本中工作。我的视频是一个包含 H264 视频和 AAC 音频的 MP4 文件(这两种编解码器都很常见并且得到广泛支持)。

您应该将视频转换为浏览器支持的格式。请参阅 this MDN 文档以查看支持的格式并注意其中的 "Browser compatibility" 部分。