【问题标题】:GoLang - Seeking through a video (serving as bytes)GoLang - 寻找视频(作为字节)
【发布时间】:2016-02-27 08:29:37
【问题描述】:

我正在用 golang 编写一个服务器,并让它提供一个基本的 .mp4 文件。它按字节提供服务。问题是我无法搜索/跳过视频。我尝试在整个 stackover flow 和谷歌中搜索以找到答案,但我没有找到答案..

这是我的代码:

package main

import (
    "net/http"
    "io/ioutil"
    "fmt"
    "os"
    "log"
    "bytes"
)

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
           // grab the generated receipt.pdf file and stream it to browser
           streamPDFbytes, err := ioutil.ReadFile("./video.mp4")
           log.Println(r)
           if err != nil {
                   fmt.Println(err)
                   os.Exit(1)
           }

           b := bytes.NewBuffer(streamPDFbytes)

           // stream straight to client(browser)
           w.Header().Set("Content-type", "video/mp4")

           if _, err := b.WriteTo(w); err != nil { // <----- here!
                   fmt.Fprintf(w, "%s", err)
           }

           w.Write([]byte("Video Completed"))
}

func main() {
    http.Handle("/", new(MyHandler))
    http.ListenAndServe(":8080", nil)
}

有没有人知道 golang 中的 seek 是如何工作的?

谢谢, 祝你有美好的一天!

【问题讨论】:

    标签: video go streaming skip seek


    【解决方案1】:

    在 Go 上流式传输 MP4 视频并寻求支持的最简单方法是

    package main
    
    import (
        "net/http"
    )
    
    func main() {
        fs := http.FileServer(http.Dir("."))
        http.Handle("/", http.StripPrefix("/", fs))
        http.ListenAndServe(":8080", nil)
    }
    

    视频将在http://localhost:8080/video.mp4提供

    更复杂的是

    package main
    
    import (
        "log"
        "net/http"
        "os"
        "time"
    )
    
    func ServeHTTP(w http.ResponseWriter, r *http.Request) {
        video, err := os.Open("./video.mp4")
        if err != nil {
            log.Fatal(err)
        }
        defer video.Close()
    
        http.ServeContent(w, r, "video.mp4", time.Now(), video)
    }
    
    func main() {
        http.HandleFunc("/", ServeHTTP)
        http.ListenAndServe(":8080", nil)
    }
    

    如果您需要更灵活的东西,您应该实现自己的progressive streaming 服务器。

    在您的代码中,您忘记添加和处理 Range/Accept-Range 标头,这就是为什么 FF 和 Chrome 都没有显示搜索栏的原因,但无论如何我认为将整个 MP4 文件保存在内存中并不好想法。

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2017-10-16
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多