阿里云oss上传的部分视频无法正常播放,使用媒体转码

据测试,qq录屏的mp4、还有原生ios录制的一些视频、上传到oss之后都无法正常播放,也就不能使用获取某一帧来作为封面截图的功能,原因是阿里云只支持H264和H265的编码

所以要给oss的视频转码,需要用到阿里云的媒体处理 (阿里云这个功能收费)

1、创建转码模板

在这里插入图片描述

2、创建管道

在这里插入图片描述

3、添加媒体Bucket输入输出

在这里插入图片描述

在这一步我遇到了一个很困扰的问题,角色错误,如下:

在这里插入图片描述
如果你也报了这个错,请走一下授权(这可是我提交阿里工单聊了一上午辛苦换来的,泪目)
AliyunMTSDefaultRole授权

4、运行代码

相关依赖

<dependency>
     <groupId>com.aliyun</groupId>
     <artifactId>aliyun-java-sdk-mts</artifactId>
     <version>2.5.2</version>
 </dependency>
import cn.hutool.core.date.DateTime;
import cn.sobuy.suocaiyun.vo.common.OSSVO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.mts.model.v20140618.SubmitJobsRequest;
import com.aliyuncs.mts.model.v20140618.SubmitJobsResponse;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.rmi.ServerException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
//我这里接收的是MultipartFile类型,所以多了一步转成FIle,你如果是File,可以去到最下方我参考的博客
public static OSSVO upload(MultipartFile file) {
    
    
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String templateId = ConstantPropertiesUtils.TEMPLATEID;
        String pipelineId = ConstantPropertiesUtils.PIPELINEID;
        OSS ossClient = null;
        try {
    
    
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String originName = file.getOriginalFilename();
            String suffix = originName.substring(originName.lastIndexOf(".") + 1).toLowerCase();

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            //调用方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            //把上传路径返回
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            //这里是因为我业务上限制了这四种类型,顺便判断一下是视频格式(我图片也走这个方法)
            List<String> fileTypes = Arrays.asList("mp4", "avi", "mov", "wmv");
            if (fileTypes.contains(suffix)) {
    
    
                //转码后的文件储存路径
                String tranUploadVideoUrl = datePath + "/(转码)" + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                // 创建DefaultAcsClient实例并初始化
                DefaultProfile profile = DefaultProfile.getProfile(
                        endpoint.substring(4, endpoint.lastIndexOf(".aliyuncs")),
                        accessKeyId,
                        accessKeySecret);
                String ossLocation = endpoint.substring(0, endpoint.indexOf(".aliyuncs"));
                IAcsClient client = new DefaultAcsClient(profile);
                // 创建API请求并设置参数
                SubmitJobsRequest request = new SubmitJobsRequest();
                // Input
                JSONObject input = new JSONObject();
                input.put("Location", ossLocation);
                input.put("Bucket", bucketName);
                try {
    
    
                    input.put("Object", URLEncoder.encode(fileName, "utf-8"));
                } catch (UnsupportedEncodingException e) {
    
    
                    throw new RuntimeException("input URL encode failed");
                }
                request.setInput(input.toJSONString());
                // Output
                String outputOSSObject;
                try {
    
    
                    outputOSSObject = URLEncoder.encode(tranUploadVideoUrl, "utf-8");
                } catch (UnsupportedEncodingException e) {
    
    
                    throw new RuntimeException("output URL encode failed");
                }
                JSONObject output = new JSONObject();
                output.put("OutputObject", outputOSSObject);
                // Ouput->Container
                JSONObject container = new JSONObject();
                container.put("Format", "mp4");
                output.put("Container", container.toJSONString());
                // Ouput->Video
                JSONObject video = new JSONObject();
                video.put("Codec", "H.264");
                video.put("Bitrate", "1500");
                video.put("Width", "1280");
                video.put("Fps", "25");
                output.put("Video", video.toJSONString());
                // Ouput->Audio
                JSONObject audio = new JSONObject();
                audio.put("Codec", "AAC");
                audio.put("Bitrate", "128");
                audio.put("Channels", "2");
                audio.put("Samplerate", "44100");
                output.put("Audio", audio.toJSONString());
                // Ouput->TemplateId
                output.put("TemplateId", templateId);
                JSONArray outputs = new JSONArray();
                outputs.add(output);
                request.setOutputs(outputs.toJSONString());
                request.setOutputBucket(bucketName);
                request.setOutputLocation(ossLocation);
                // PipelineId
                request.setPipelineId(pipelineId);
                // 发起请求并处理应答或异常
                SubmitJobsResponse response = client.getAcsResponse(request);
                System.out.println("RequestId is:" + response.getRequestId());
                if (response.getJobResultList().get(0).getSuccess()) {
    
    
                    System.out.println("JobId is:" + response.getJobResultList().get(0).getJob().getJobId());
                } else {
    
    
                    System.out.println("SubmitJobs Failed code:" + response.getJobResultList().get(0).getCode() +
                            " message:" + response.getJobResultList().get(0).getMessage());
                }
                url = "https://" + bucketName + "." + endpoint + "/" + tranUploadVideoUrl;
            }

            return new OSSVO(url, originName, suffix);
        } catch (ServerException e) {
    
    
            e.printStackTrace();
        } catch (ClientException e) {
    
    
            e.printStackTrace();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            ossClient.shutdown();
        }

        // 关闭OSSClient。
        return null;
    }

在这里插入图片描述

打印如上说明任务创建成功,注意,是创建成功,它是创建了一个转码任务,但还没完成,可以到任务管理里去查看具体状态

在这里插入图片描述

仔细看代码会发现转码后是生成了新的地址,我试了一下用原来的地址,是不行的,大概是因为转码用到了原视频,而oss同名文件会直接覆盖,会有冲突。

相关链接:oss视频截帧媒体处理
参考博客:https://blog.csdn.net/weixin_48173054/article/details/121330563

猜你喜欢

转载自blog.csdn.net/shuttle33/article/details/127320042