본문 바로가기

Spring Boot

[SpringBoot] MP4 파일을 M3U8 파일로 변환

반응형
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class ConvertController {
  @PostMapping("/convert")
  public String convert(@RequestParam("file") MultipartFile file) throws IOException, InterruptedException {
    if (file.isEmpty()) {
      return "Please select a file to convert.";
    }

    File tempFile = File.createTempFile("input", ".mp4");
    file.transferTo(tempFile);

    File outputFile = new File("output.m3u8");
    String command = String.format("ffmpeg -i %s -codec copy -hls_time 10 -hls_list_size 0 %s",
        tempFile.getAbsolutePath(), outputFile.getAbsolutePath());
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();

    return "Conversion successful.";
  }
}

 MultipartFile 형식의 파일을 수락하고 서버의 임시 파일에 씁니다. 그런 다음 ffmpeg 명령줄 도구를 사용하여 MP4 파일을 M3U8 파일로 변환합니다. 출력은 스프링 부트 응용 프로그램과 동일한 디렉터리에 output.m3u8이라는 파일에 저장됩니다.

이 코드는 ffmpeg가 서버에 설치되어 있고 명령줄에서 사용할 수 있다고 가정합니다. 그렇지 않으면 먼저 설치하거나 코드를 수정하여 다른 변환 도구를 사용해야 할 수 있습니다. 또한 예외를 처리하고 보다 강력한 오류 처리를 제공하기 위해 코드를 수정해야 할 수도 있습니다.

반응형