调用JSch实现mp4转m3u8格式

文章说明

今天记录一下通过JSch实现MP4转m3u8格式文件。另外,如果需要转载我的文章,请表明文章出处及作者。https://blog.csdn.net/caleb_520/article/details/131701421?spm=1001.2014.3001.5502

实现方法

  1. ProcessBuilder ,这个是通过java调用cmd命令
  2. JSch,由Java实现的SSH2协议的库,它提供了一种在Java程序中连接和操作SSH服务器的方式。它允许你通过SSH协议在本地和远程机器之间建立安全的通信连接,并通过SFTP协议进行文件传输

采用JSch实现mp4转m3u8

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUploader {
    public static void main(String[] args) {
        // 指定本地待上传的文件路径
        String localFilePath = "/path/to/local/file.mp4";
        // 指定远程服务器存储路径
        String remoteFilePath = "/path/to/remote/file.mp4";

        // 上传文件到远程服务器
        uploadFile(localFilePath, remoteFilePath);

        // 执行FFmpeg转码操作
        transcodeFile(remoteFilePath);
    }

    private static void uploadFile(String localFilePath, String remoteFilePath) {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession("your_username", "server_address", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("your_password");
            session.connect();

            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            String command = "scp " + localFilePath + " user@server:" + remoteFilePath;
            channel.setCommand(command);
            channel.connect();
            channel.disconnect();

            session.disconnect();

            System.out.println("文件上传成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件上传失败!");
        }
    }

    private static void transcodeFile(String remoteFilePath) {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession("your_username", "server_address", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("your_password");
            session.connect();

            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            String command = "ffmpeg -i " + remoteFilePath + " -c:v copy -c:a copy transcoded.mp4";
            channel.setCommand(command);

            StringBuilder output = new StringBuilder();
            InputStream in = channel.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            channel.connect();

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            channel.disconnect();
            session.disconnect();

            System.out.println("文件转码成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件转码失败!");
        }
    }
}

转换方式,大家可以参考代码中的transcodeFile

你可能感兴趣的:(调用JSch实现mp4转m3u8格式)