1. 最初に, 500M を超えないビデオをフロントエンドに提供する方法について話させてください. この方法は比較的高速ですが, フロントエンドには優しくありません. ブラウザは特に大きなサイズを再生できません.ビデオファイル。
以下は、Java コードの例です。
この方法では、依存関係を導入する必要はありません。最初に構成する
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;
@Component
public class NonStaticResourceHttpRequestConfig 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);
}
}
次にインターフェースを書きます。
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xr.config.NonStaticResourceHttpRequestConfig;
import com.xr.config.XrConfig;
import com.xr.domain.AjaxResult;
import com.xr.utils.file.FileUtils;
import com.xr.video.domain.VideoShow;
import com.xr.video.mapper.VideoShowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
//接口:前端视频上传
@RestController
//一级地址
@RequestMapping("/uploadVideoController")
public class UploadVideoController {
@Autowired
private VideoShowMapper videoShowMapper;
@Autowired
private NonStaticResourceHttpRequestConfig nonStaticResourceHttpRequestConfig;
@Autowired
private XrConfig xrConfig;
//二级地址
@PostMapping(value = "/uploadVideo")
@ResponseBody
//Map<String,String>: map是键值对形式组成的集合,类似前端的数组但是里面是键值对形式的,前后两个string代表键和值都是字符串格式的。
//post请求传入的参数:MultipartFile file(理解为springmvc框架给我们提供的工具类,代表视频流数据),SavePath(前台传来的地址路径,也是用来后端保存在服务器哪个文件夹的地址)
public AjaxResult savaVideoTest(@RequestParam("file") MultipartFile file)
//throws IllegalStateException写在方法的前面是可以抛出异常状态的,如果有错误会把错误信息发出来对应下面的try和catch
throws IllegalStateException {
//new一个map集合出来
String videoPath = xrConfig.getVideoPath();
// Map<String, String> resultMap = new HashMap<>();
try {
//获取文件后缀,因此此后端代码可接收一切文件,上传格式前端限定
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
// 重构文件名称
//UUID(全局唯一标识符)randomUUID(随机生成标识符)toString(转成字符串)replaceAll(替换字符方法,因为随机生成的里面包括了 - ,这里意思是把 - 全部换成空)
String pikId = UUID.randomUUID().toString().replaceAll("-", "");
//视频名字拼接:唯一标识符加上点,再加上上面的视频后缀也就是MP4之类的。就组成了现在的视频名字,比如这样:c7bbc1f9664947a287d35dd7cdc48a95.mp4
String newVideoName = pikId + "." + fileExt;
System.out.println("重构文件名防止上传同名文件:" + newVideoName);
//保存视频的原始名字
String videoNameText = file.getOriginalFilename();
System.out.println("视频原名:" + videoNameText);
//保存视频url路径地址
String videoUrl = videoPath + File.separator + newVideoName;
//获取上一次文件的信息
LambdaQueryWrapper<VideoShow> lambdaQueryWrapperdemo = new LambdaQueryWrapper<>();
VideoShow selectOne = videoShowMapper.selectOne(lambdaQueryWrapperdemo);
if (null != selectOne) {
//清空上一次的数据
LambdaQueryWrapper<VideoShow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
videoShowMapper.delete(lambdaQueryWrapper);
//删除所有文件
if (!(FileUtils.deleteFile(videoPath + File.separator + selectOne.getVideoName()))) {
return AjaxResult.error("删除上一次文件失败");
}
}
//调用数据库接口插入数据库方法save,把视频原名,视频路径,视频的唯一标识码传进去存到数据库内
VideoShow videoShow = new VideoShow();
videoShow.setId(IdUtil.randomUUID());
videoShow.setVideoName(newVideoName);
videoShow.setVideoUrl(videoUrl);
videoShow.setVideoUuid(IdUtil.simpleUUID());
videoShowMapper.insert(videoShow);
//判断SavePath这个路径也就是需要保存视频的文件夹是否存在
File filepath = new File(videoPath, file.getOriginalFilename());
if (!filepath.getParentFile().exists()) {
//如果不存在,就创建一个这个路径的文件夹。
filepath.getParentFile().mkdirs();
}
//保存视频:把视频按照前端传来的地址保存进去,还有视频的名字用唯一标识符显示,需要其他的名字可改这
File fileSave = new File(videoPath, newVideoName);
//下载视频到文件夹中
file.transferTo(fileSave);
//构造Map将视频信息返回给前端
//视频名称重构后的名称:这里put代表添加进map集合内,和前端的push一样。括号内是前面字符串是键,后面是值
// resultMap.put("newVideoName", newVideoName);
//正确保存视频成功,则设置返回码为200
// resultMap.put("resCode", "200");
//返回视频保存路径
// resultMap.put("VideoUrl", videoPath + "/" + newVideoName);
//到这里全部保存好了,把整个map集合返给前端
return AjaxResult.success("视频上传成功");
} catch (Exception e) {
//在命令行打印异常信息在程序中出错的位置及原因
e.printStackTrace();
//返回有关异常的详细描述性消息。
e.getMessage();
//保存视频错误则设置返回码为400
// resultMap.put("resCode", "400");
//这时候错误了,map里面就添加了错误的状态码400并返回给前端看
return AjaxResult.error("上传失败");
}
}
@GetMapping("/getVideoShipin")
public void getVideoShipin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用查询方法,把前端传来的id传过去,查询对应的视频信息。
LambdaQueryWrapper<VideoShow> lambdaQueryWrapper = new LambdaQueryWrapper<>();
VideoShow videoPathList = videoShowMapper.selectOne(lambdaQueryWrapper);
//从视频信息中单独把视频路径信息拿出来保存
String videoPathUrl = videoPathList.getVideoUrl();
//保存视频磁盘路径
Path filePath = Paths.get(videoPathUrl);
//Files.exists:用来测试路径文件是否存在
if (Files.exists(filePath)) {
//获取视频的类型,比如是MP4这样
File file = new File(videoPathUrl);
String mimeType = Files.probeContentType(filePath);
if (StrUtil.isNotEmpty(mimeType)) {
//判断类型,根据不同的类型文件来处理对应的数据
response.setContentType(mimeType);
response.addHeader("Content-Length", "" + file.length());
}
//转换视频流部分
request.setAttribute(NonStaticResourceHttpRequestConfig.ATTR_FILE, filePath);
nonStaticResourceHttpRequestConfig.handleRequest(request, response);
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
}
}
}
メソッドを呼び出し、http://192.168.10.88:10001/ uploadVideoController/getVideoShipin ブラウザでインターフェイス リンクを直接開き、自動的に再生します。ただし、大きなファイルを再生するには読み込みを待つ必要があり、非常に遅くなります。
したがって、2 番目の方法をお勧めします
Spring Boot は ffmpeg を統合し、m3u8 スライスを使用して再生します。
1. まず、ffmpeg プラグインをインストールする必要があります。
ffmpeg プラグインは、Windows、Linux、および Mac OS にインストールできるクロスプラットフォーム ソフトウェアです。
Windows インストールのチュートリアルは次のとおりです。
1. ダウンロードの準備
01. 公式サイトのダウンロード: https://ffmpeg.org/download.htmlこれをクリックして
github に入り、リソースを見つけてダウンロードします。
02. Github ダイレクト リンク ダウンロード: https://github.com/BtbN/FFmpeg-Builds/releases
03. Lanzout クラウド ダウンロード: https://pla.lanzout.com/i5SP7ysw7ta
2.インストール
これをダウンロードし、該当するフォルダに解凍してください。
bin フォルダーを開き、このパスをコピーして、システム変数に追加します。
私の例では、D:\ffmpeg\bin を取り上げます。
この PC の空きスペースを右クリックし、[プロパティ] を選択します。
環境変数の選択
[ユーザー環境変数] でパスをダブルクリックし、[編集] を選択します。
[新規] を選択し、コピーしたばかりのビン パスを貼り付けて、[OK] をクリックします。
下部にある [OK] をクリックし、現在のウィンドウを閉じて [OK] をクリックして保存することを忘れないでください。[キャンセル] をクリックしないでください。
最後に、行のウィンドウを閉じます。
3. 検証とテスト
ここまでで ffmpeg の設定はほぼ完了です. コマンドラインを呼び出して (windows+R から cmd を入力), 「ffmpeg –version」と入力して以下の結果が表示されたら, 設定は成功です.
2.POM ファイルを構成する
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<java.version>11</java.version>
<javacv.version>1.5.4</javacv.version>
<ffmpeg.version>4.3.1-1.5.4</ffmpeg.version>
</properties>
<dependencies>
<!-- javacv 和 ffmpeg的依赖包 -->
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>${javacv.version}</version>
<exclusions>
<exclusion>
<groupId>org.bytedeco</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>${ffmpeg.version}</version>
</dependency>
</dependencies>
</project>
3. 情報ファイルと鍵ファイルを構成する
上記の test.info と test.key を構成する必要があります。
2 つのファイルは次のとおりで、直接再利用できます。
test.info の内容は次のとおりです。
- 外部アクセス キー ファイルのアドレス
- 実行中にキーのアドレスにアクセスする
- 鍵
http://192.168.10.88:10001/m3u8controller/preview/test.key
http://192.168.10.88:10001/m3u8controller/preview/test.key
682f5033538cf71567e1bdb38f5f9a07
test.key の内容は次のとおりです。
n4DHLX7kmPeewvW3dGlm5i/EE8I
4. 処理クラスとコントローラーを作成する
このクラスの http パスを実際のパスに置き換えることを忘れないでください。
ここで、次のコードをコメントアウトして、暗号化を行わないようにすることができます
//recorder.setOption("hls_key_info_file", infoUrl);
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;
import java.io.IOException;
import java.io.InputStream;
/**
* @author : xuansy
* @version : 1.0
* @date : 2021/5/21 22:46
* @project_name: ffmpeg-demo
* @package_name : com.example.ffmpeg.demo.processor
* @name: FFmpegProcessor
* @email: [email protected]
* @description :
*/
public class FFmpegProcessor {
/**
* 这个方法的url地址都必须是一样的类型 同为post
*/
public static void convertMediaToM3u8ByHttp(InputStream inputStream, String m3u8Url, String infoUrl) throws IOException {
avutil.av_log_set_level(avutil.AV_LOG_INFO);
FFmpegLogCallback.set();
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputStream);
grabber.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(m3u8Url, grabber.getImageWidth(), grabber.getImageHeight(), grabber.getAudioChannels());
recorder.setFormat("hls");
recorder.setOption("hls_time", "5");
recorder.setOption("hls_list_size", "0");
recorder.setOption("hls_flags", "delete_segments");
recorder.setOption("hls_delete_threshold", "1");
recorder.setOption("hls_segment_type", "mpegts");
recorder.setOption("hls_segment_filename", "http://localhost:8080/upload/test-%d.ts");
recorder.setOption("hls_key_info_file", infoUrl);
// http属性
recorder.setOption("method", "POST");
recorder.setFrameRate(25);
recorder.setGopSize(2 * 25);
recorder.setVideoQuality(1.0);
recorder.setVideoBitrate(10 * 1024);
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
recorder.start();
Frame frame;
while ((frame = grabber.grabImage()) != null) {
try {
recorder.record(frame);
} catch (FrameRecorder.Exception e) {
e.printStackTrace();
}
}
recorder.setTimestamp(grabber.getTimestamp());
recorder.close();
grabber.close();
}
}
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.example.ffmpeg.demo.processor.FFmpegProcessor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author : xuansy
* @version : 1.0
* @date : 2021/5/21 22:45
* @project_name: ffmpeg-demo
* @package_name : com.example.ffmpeg.demo.controller
* @name: TestController
* @email: [email protected]
* @description :
*/
@RestController
public class TestController {
/**
* 目录路径,这个路径需要包含test.info文件,test.key文件和test.mp4文件
*/
private static final String PATH = "D:\\test\\";
@PostMapping("uploadToM3u8")
public void uploadToM3u8() throws Exception {
FileInputStream inputStream = new FileInputStream(PATH + "test.mp4");
String m3u8Url = "http://localhost:8080/upload/test.m3u8";
String infoUrl = "http://localhost:8080/preview/test.info";
FFmpegProcessor.convertMediaToM3u8ByHttp(inputStream, m3u8Url, infoUrl);
}
@PostMapping("upload/{fileName}")
public void upload(HttpServletRequest request, @PathVariable("fileName") String fileName) throws IOException {
ServletInputStream inputStream = request.getInputStream();
FileWriter writer = new FileWriter(PATH + fileName);
writer.writeFromStream(inputStream);
IoUtil.close(inputStream);
}
/**
* 预览加密文件
*/
@PostMapping("preview/{fileName}")
public void preview(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
FileReader fileReader = new FileReader(PATH + fileName);
fileReader.writeToStream(response.getOutputStream());
}
/**
* 预览加密文件
*/
@GetMapping("download/{fileName}")
public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
FileReader fileReader = new FileReader(PATH + fileName);
fileReader.writeToStream(response.getOutputStream());
}
}
springboot を起動し、次のグラフィック操作を実行して、http テスト ファイルを生成します。
クリックして実行し、http リクエストが実行されるのを待つと、ディレクトリに m3u8 ファイルと ts ファイルが生成されていることがわかります。
この時点で、変更する必要がある場所が 1 つあります。それは、 m3u8 のキーhttp要求アドレスです。この例はすべて投稿であるため、後でブラウザーをテストするときにメソッドをサポートしません。前のものを削除します。直接、
このように、キーを要求すると、m3u8 によって要求されたアドレス プレフィックスがデフォルトになります。
次に Chrome ブラウザを開き、Play HLS M3u8 プラグインをインストールします. インストールされていない場合は、m3u8 をオフラインで再生できるソフトウェアを探します.
この時点で、ビデオは m3u8 ファイルにスライスされ、暗号化されます。ご覧いただきありがとうございます。