春季启动+ HTML 5视频流

5 java html5 html5-video thymeleaf spring-boot

我最近一直在学习Spring启动框架,到目前为止,我对它印象深刻。

但是,我一直在尝试编写一个基本的媒体服务器应用程序,但我不完全确定实现提供HTML 5视频源的控制器端点的正确方法是什么。我目前已经这样实现了:

@GetMapping(value = "/videosrc", produces = "video/mp4")
@ResponseBody
public FileSystemResource videoSource(@RequestParam(value="id", required=true) int id) {
    return new FileSystemResource(new File("path to mp4 file"));
}
Run Code Online (Sandbox Code Playgroud)

HTML 5视频元素如下所示:(使用Thymeleaf)

<video width="auto" height="240" controls style=" margin-left: auto; margin-right: auto; display: block;">
    <source th:src="@{/videosrc(id=${video.id})}" type="video/mp4">
</video>
Run Code Online (Sandbox Code Playgroud)

视频显示出来,但是我注意到,如果我跳过视频几次,它最终会变慢,然后冻结浏览器。我不确定为什么会这样,但是我认为是因为我没有正确处理请求?

谢谢

Pau*_*ren 7

您应该考虑一个名为Spring Content的 Spring Boot 配套项目,它允许您用很少的代码创建数字资产管理应用程序。

给你一个看起来像这样的基本想法:-

pom.xml

<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>spring-content-rest-boot-starter</artifactId>
    <version>0.0.10</version>
</dependency>
<dependency>
    <groupId>com.github.paulcwarren</groupId>
    <artifactId>content-fs-spring-boot-starter</artifactId>
    <version>0.0.10</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

SpringBootApplication.java

@SpringBootApplication
public class YourSpringBootApplication {

  public static void main(String[] args) {
    SpringApplication.run(YourSpringBootApplication.class, args);
  }

  @Configuration
  @EnableFilesystemStores
  public static class StoreConfig {
    File filesystemRoot() {
        // return the root of your video store
    }

    // this bean is the spring resource loader that will be used by
    // the product store  
    @Bean
    public FileSystemResourceLoader fsResourceLoader() throws Exception 
    {
      return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
    }
  }

  @StoreRestResource(path="videosrc")
  public interface VideoStore extends Store<String> {
    //
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您没有在此处编写任何控制器代码,但这足以创建/videosrc支持完整 CRUD 和视频流(即字节范围)的 REST 视频服务。创建 == POST、读取 == GET(包括字节范围支持)、更新 == PUT、删除 == DELETE。

例如

POST /videosrc/some/path/video1.mp4

将上传的多部分视频存储到 /some/path/video.mp4。

Spring Content 也可以与 Spring Data 结合来存储和搜索关于这些视频的元数据。如果您对此感兴趣,请查看此处此处的入门指南。


小智 1

看起来这可能只是 Firefox (Quantum) 的问题 - 它工作正常,但跳过几次后似乎冻结了。

我在 Google Chrome 上测试了这个,效果很好。在移动浏览器上也能正常工作。

我还检查了它是否发送了正确的 HTTP 标头 - 主要是“Accept-Ranges: bytes”(确实如此)。