unity c# ffmpeg 获取mp4 文件长度
时间: 2023-08-24 21:15:21 浏览: 164
你可以使用FFmpeg库中的AVFormatContext和AVCodecContext来获取视频文件的长度。以下是一个示例代码:
```c#
using UnityEngine;
using FFmpeg.AutoGen;
using System;
public class VideoInfo : MonoBehaviour
{
void Start()
{
string filePath = "path/to/your/video.mp4";
AVFormatContext* formatContext = null;
AVCodecContext* codecContext = null;
ffmpeg.av_register_all();
ffmpeg.avcodec_register_all();
int result = ffmpeg.avformat_open_input(&formatContext, filePath, null, null);
if (result != 0)
{
Debug.LogError("Failed to open video file: " + result);
return;
}
result = ffmpeg.avformat_find_stream_info(formatContext, null);
if (result < 0)
{
Debug.LogError("Failed to find video stream information: " + result);
ffmpeg.avformat_close_input(&formatContext);
return;
}
int videoStreamIndex = -1;
for (int i = 0; i < formatContext->nb_streams; i++)
{
if (formatContext->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
{
videoStreamIndex = i;
break;
}
}
if (videoStreamIndex == -1)
{
Debug.LogError("Failed to find video stream in file");
ffmpeg.avformat_close_input(&formatContext);
return;
}
codecContext = formatContext->streams[videoStreamIndex]->codec;
double videoLengthInSeconds = (double)formatContext->duration / ffmpeg.AV_TIME_BASE;
Debug.Log("Video length: " + TimeSpan.FromSeconds(videoLengthInSeconds).ToString(@"hh\:mm\:ss"));
ffmpeg.avformat_close_input(&formatContext);
}
}
```
该代码使用FFmpeg库打开指定的视频文件,找到视频流并从中提取信息,最后计算出视频的长度。需要注意的是,该代码使用了一些不安全的指针操作,请确保你的代码环境支持使用指针。
阅读全文
相关推荐













