溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot靜態(tài)視頻實(shí)時(shí)播放的實(shí)現(xiàn)代碼怎么編寫

發(fā)布時(shí)間:2021-11-24 14:23:37 來源:億速云 閱讀:204 作者:柒染 欄目:編程語言

今天就跟大家聊聊有關(guān)SpringBoot靜態(tài)視頻實(shí)時(shí)播放的實(shí)現(xiàn)代碼怎么編寫,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

問題描述

Spring Boot API 定義 GET 請(qǐng)求 API , 返回視頻流。前端通過 <video> 標(biāo)簽加載并播放視頻,效果是必須等整個(gè)視頻資源全部加載到瀏覽器才能播放,而且 <video> 標(biāo)簽?zāi)J(rèn)的進(jìn)度條無法控制視頻的播放。最終希望的效果是視頻流邊加載邊播放,且播放器的控制正常使用。

解決方法

Spring Framework 文件請(qǐng)求處理

import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.stereotype.Component;import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;import javax.servlet.http.HttpServletRequest;import java.nio.file.Path;@Componentpublic class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {  public final static String ATTR_FILE = "NON-STATIC-FILE";  @Override  protected Resource getResource(HttpServletRequest request) {    final Path filePath = (Path) request.getAttribute(ATTR_FILE);    return new FileSystemResource(filePath);  }}

Controller 層

@RestController@AllArgsConstructorpublic class FileRestController {  private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;  /**   * 預(yù)覽視頻文件, 支持 byte-range 請(qǐng)求   */  @GetMapping("/video")  public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {    String path = request.getParameter("path");    Path filePath = Paths.get(path);    if (Files.exists(filePath)) {      String mimeType = Files.probeContentType(filePath);      if (!StringUtils.isEmpty(mimeType)) {        response.setContentType(mimeType);      }      request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);      nonStaticResourceHttpRequestHandler.handleRequest(request, response);    } else {      response.setStatus(HttpServletResponse.SC_NOT_FOUND);      response.setCharacterEncoding(StandardCharsets.UTF_8.toString());    }  }}

看完上述內(nèi)容,你們對(duì)SpringBoot靜態(tài)視頻實(shí)時(shí)播放的實(shí)現(xiàn)代碼怎么編寫有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI