Java动态处理m3u8问题
原始m3u8文件
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:20
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:20.500000,
00000.ts
#EXTINF:20.266667,
00001.ts
#EXTINF:20.266667,
00002.ts
#EXTINF:9.900000,
00003.ts
#EXT-X-ENDLIST
修改后m3u8文件
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:20
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:20.500000,
/data/test/00000.ts
#EXTINF:20.266667,
/data/test/00001.ts
#EXTINF:20.266667,
/data/test/00002.ts
#EXTINF:9.900000,
/data/test/00003.ts
#EXT-X-ENDLIST
Java 动态修改m3u8地址播放
package com.xxx.xxx.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
@Slf4j
@RestController
public class TestController {
@GetMapping(value = {"/play/{id}", "/play/{id}/"})
public void videoPay(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setCharacterEncoding("utf-8");
try {
String targetPathM3u8 = "/xxx/xxx.m3u8";
byte[] targetByte = Files.readAllBytes(Paths.get(targetPathM3u8));
StringBuffer stringBuffer = new StringBuffer();
byte[] bytes = new byte[]{};
String m3u8Str = new String(targetByte);
if(!StringUtils.isEmpty(m3u8Str)) {
String[] split = m3u8Str.split(System.lineSeparator());
Arrays.stream(split).forEach(ts -> {
if (stringBuffer.length() != 0) {
stringBuffer.append(System.lineSeparator());
}
if (!StringUtils.isEmpty(ts) && ts.endsWith(".ts")) {
String formatBytes = String.format("%s/%s", "自定义URL", ts);
stringBuffer.append(formatBytes);
return;
}
stringBuffer.append(ts);
});
bytes = stringBuffer.toString().getBytes(StandardCharsets.UTF_8);
}
Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(targetPathM3u8);
if (mediaType.isPresent()){
response.setCharacterEncoding("utf-8");
response.setContentType(mediaType.get().toString());
response.setHeader("Accept-Ranges", "bytes");
os.write(bytes);
}
}finally {
os = null;
}
}
}