Springboot+FFmepg 实现直播功能-推流和拉流

748 阅读1分钟


@RestController
public class VideoController {

  private static final String INPUT_PATH = "D:/video/1.mp4";
  private static final String OUTPUT_URL = "rtmp://localhost/live/stream";

  @RequestMapping("/pushstream")
  public void pushStream() throws IOException {
    FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(INPUT_PATH);
    grabber.start();

    FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(OUTPUT_URL, grabber.getImageWidth(), grabber.getImageHeight());
    recorder.setVideoCodec(AV_CODEC_ID_H264);
    recorder.setFormat("flv");
    recorder.start();

    Frame frame;
    while ((frame = grabber.grabFrame()) != null) {
      recorder.record(frame);
    }

    grabber.stop();
    recorder.stop();
  }

  @RequestMapping("/pullstream")
  public void pullStream(HttpServletResponse response) throws IOException, URISyntaxException {
    FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(OUTPUT_URL);
    grabber.start();

    response.setContentType("video/mp4");
    ServletOutputStream outputStream = response.getOutputStream();

    Frame frame;
    while ((frame = grabber.grabFrame()) != null) {
      BufferedImage img = new Java2DFrameConverter().getBufferedImage(frame);
      ImageIO.write(img, "mp4", outputStream);
    }

    outputStream.flush();
    outputStream.close();
    grabber.stop();
  }
}

//以上代码实现了两个 RESTful 接口,
// /pushstream 用于处理推流请求,将本地视频文件推流到RTMP服务器上;
// /pullstream 用于处理拉流请求,从RTMP服务器上拉取视频流,实时将视频数据流传输给HTTP客户端。

启动Springboot应用,分别访问 http://localhost:8080/pushstreamhttp://localhost:8080/pullstream,即可实现视频直播功能。在 http://localhost:8080/pullstream 的视频播放页面中,将自动播放从RTMP服务器上拉取到的视频流。

需要注意的是,以上示例代码并不是完整的视频直播系统,其中的推流和拉流功能只是最基础的实现方式