音频视频处理:获取指定视频流链接的时长,获取指定音频流链接的时长
文章目录
- 需求
- 分析
- 视频
- 音频
- 方式一
- 方式二
- 其他:测试地址:音视频链接
- MP4 格式
- M3U8 格式
- MP3 音频文件
- 音视频裁剪
需求
在上传音视频后,后端会返回一个视频地址,如何根据该地址获取音视频的时长

分析
视频
利用浏览器的 HTMLVideoElement 对象加载视频的元数据(无需下载完整视频),从而获取精准的时长(秒数)
- 思路
/**
* 获取远程视频的时长(单位:秒)
* @param {string} videoUrl - 视频链接
* @returns {Promise} 视频时长(秒,保留两位小数)
*/
async function getVideoDurationInSeconds(videoUrl) {
return new Promise((resolve, reject) => {
// 创建 video 元素(无需添加到 DOM)
const video = document.createElement('video');
// 关键:设置跨域配置(若视频服务器允许跨域,需添加此属性)
video.crossOrigin = 'anonymous'; // 或 'use-credentials'(根据服务器配置)
// 监听元数据加载完成事件(此时已能获取时长)
video.onloadedmetadata = () => {
// video.duration 是视频总时长(单位:秒,可能是小数,如 120.5 秒)
const duration = Number(video.duration.toFixed(2)); // 保留两位小数
// 释放资源
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(video.src); // 清理临时 URL
resolve(duration);
};
// 监听错误事件(如跨域、地址无效、格式不支持)
video.onerror = (err) => {
reject(new Error(`获取视频时长失败:${video.error?.code || '未知错误'}`));
// 释放资源
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(video.src);
};
// 监听加载超时(可选,防止长时间无响应)
setTimeout(() => {
reject(new Error('获取视频时长超时'));
}, 10000); // 10秒超时
// 设置视频地址,触发元数据加载
video.src = videoUrl;
// 强制加载元数据(部分浏览器需要)
video.load();
});
}
// 调用示例
const videoUrl = "https://www.dkifly.com/ifly-api/admin-api/infra/file/29/get/20251212/bbb4cc64216dac72124369fd35b7ae00_1765533865580.mp4";
getVideoDurationInSeconds(videoUrl)
.then(duration => {
console.log('视频时长(秒):', duration); // 输出示例:125.36
})
.catch(error => {
console.error(error.message);
});
- 总代码
<template>
<div>
<el-button @click="fetchVideoDuration">获取视频时长</el-button>
<div v-if="duration !== null">视频时长(秒):{{ duration }}</div>
<div v-if="errorMsg">错误:{{ errorMsg }}</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const duration = ref<number | null>(null);
const errorMsg = ref('');
/**
* 获取远程视频的时长(单位:秒)
* @param {string} videoUrl - 视频链接
* @returns {Promise} 视频时长(秒)
*/
const getVideoDurationInSeconds = async (videoUrl: string): Promise<number> => {
return new Promise((resolve, reject) => {
const video = document.createElement('video');
video.crossOrigin = 'anonymous';
video.onloadedmetadata = () => {
const duration = Number(video.duration.toFixed(2));
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(video.src);
resolve(duration);
};
video.onerror = () => {
reject(new Error('视频加载失败,可能是跨域或链接无效'));
video.removeAttribute('src');
video.load();
URL.revokeObjectURL(video.src);
};
// 10秒超时
setTimeout(() => {
reject(new Error('获取时长超时,请检查视频链接'));
}, 10000);
video.src = videoUrl;
video.load();
});
};
// 触发获取时长
const fetchVideoDuration = async () => {
const videoUrl = "https://www.dkifly.com/ifly-api/admin-api/infra/file/29/get/20251212/bbb4cc64216dac72124369fd35b7ae00_1765533865580.mp4";
try {
duration.value = await getVideoDurationInSeconds(videoUrl);
errorMsg.value = '';
} catch (err) {
duration.value = null;
errorMsg.value = (err as Error).message;
}
};
</script>
音频
方式一
核心逻辑和视频是一样的
- 思路
/**
* 获取远程音频/视频的时长(单位:秒,适配 MP3/MP4 等格式)
* @param {string} mediaUrl - 音频/视频链接(MP3/MP4 均可)
* @returns {Promise} 时长(秒,保留两位小数)
*/
async function getMediaDurationInSeconds(mediaUrl) {
return new Promise((resolve, reject) => {
// 针对音频,使用 audio 元素(语义化,性能更优)
const media = document.createElement('audio'); // 替换为 audio 元素
// 跨域配置(关键:需服务器支持 CORS)
media.crossOrigin = 'anonymous';
// 元数据加载完成:获取时长
media.onloadedmetadata = () => {
if (isNaN(media.duration)) {
reject(new Error('无法获取媒体时长,可能是文件格式不支持或元数据缺失'));
return;
}
// 转换为秒(保留两位小数)
const duration = Number(media.duration.toFixed(2));
// 释放资源,避免内存泄漏
media.removeAttribute('src');
media.load();
URL.revokeObjectURL(media.src);
resolve(duration);
};
// 错误处理(跨域、链接无效、格式不支持等)
media.onerror = (err) => {
reject(new Error(`获取时长失败:${media.error?.message || '未知错误'}`));
media.removeAttribute('src');
media.load();
URL.revokeObjectURL(media.src);
};
// 超时处理(防止长时间无响应)
setTimeout(() => {
reject(new Error('获取时长超时(10秒)'));
}, 10000);
// 设置媒体地址,触发加载
media.src = mediaUrl;
media.load();
});
}
// 调用示例:音频链接(MP3)
const audioUrl = "https://www.dkifly.com/ifly-api/admin-api/infra/file/29/get/20251212/bbb4cc64216dac72124369fd35b7ae00_1765533865580.mp3";
getMediaDurationInSeconds(audioUrl)
.then(duration => {
console.log('音频时长(秒):', duration); // 输出示例:120.56
})
.catch(error => {
console.error(error.message);
});
// 调用示例:视频链接(MP4)(该函数也兼容视频)
const videoUrl = "https://www.dkifly.com/ifly-api/admin-api/infra/file/29/get/20251212/bbb4cc64216dac72124369fd35b7ae00_1765533865580.mp4";
getMediaDurationInSeconds(videoUrl)
.then(duration => {
console.log('视频时长(秒):', duration);
})
.catch(error => {
console.error(error.message);
});
- 总代码
<template>
<div>
<el-button @click="fetchAudioDuration">获取音频时长</el-button>
<div v-if="duration !== null">音频时长(秒):{{ duration }}</div>
<div v-if="errorMsg" style="color: red;">{{ errorMsg }}</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const duration = ref<number | null>(null);
const errorMsg = ref('');
/**
* 通用方法:获取音频/视频时长(秒)
*/
const getMediaDurationInSeconds = async (mediaUrl: string): Promise<number> => {
return new Promise((resolve, reject) => {
const media = document.createElement('audio');
media.crossOrigin = 'anonymous';
media.onloadedmetadata = () => {
if (isNaN(media.duration)) {
reject(new Error('媒体文件元数据缺失,无法获取时长'));
return;
}
const duration = Number(media.duration.toFixed(2));
media.removeAttribute('src');
media.load();
URL.revokeObjectURL(media.src);
resolve(duration);
};
media.onerror = () => {
reject(new Error('加载失败:可能是跨域、链接无效或格式不支持'));
media.removeAttribute('src');
media.load();
URL.revokeObjectURL(media.src);
};
setTimeout(() => {
reject(new Error('获取时长超时,请检查链接'));
}, 10000);
media.src = mediaUrl;
media.load();
});
};
// 触发获取音频时长
const fetchAudioDuration = async () => {
const audioUrl = "https://www.dkifly.com/ifly-api/admin-api/infra/file/29/get/20251212/bbb4cc64216dac72124369fd35b7ae00_1765533865580.mp3";
try {
duration.value = await getMediaDurationInSeconds(audioUrl);
errorMsg.value = '';
} catch (err) {
duration.value = null;
errorMsg.value = (err as Error).message;
}
};
</script>
方式二
async function getAudioDuration(url) {
return new Promise((resolve, reject) => {
const audio = new Audio(url)
audio.addEventListener('loadedmetadata', () => {
console.log(audio.duration)
// 返回四舍五入后的秒数
resolve(Math.round(audio.duration))
})
audio.addEventListener('error', (e) => {
reject(new Error('Failed to load audio file'))
})
})
}
// 使用
try {
const duration = await getAudioDuration('https://example.com/audio.mp3');
console.log(`音频时长: ${duration} 秒`)
} catch (error) {
console.error('获取音频时长失败:', error.message)
}
获取时分秒
async function getFormattedDuration(url) {
const duration = await getAudioDuration(url);
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// 使用示例
const formattedDuration = await getFormattedDuration('https://example.com/audio.mp3');
console.log(`音频时长: ${formattedDuration}`); // 输出格式如: "3:45"
其他:测试地址:音视频链接
MP4 格式
- 海洋:http://vjs.zencdn.net/v/oceans.mp4
- 西瓜视频 Demo:https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4
- 大兔子:http://www.w3school.com.cn/example/html5/mov_bbb.mp4
- 大灰熊:https://www.w3schools.com/html/movie.mp4
- 冰川:https://media.w3.org/2010/05/sintel/trailer.mp4
- 新闻视频1:https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209105011F0zPoYzHry.mp4
- 新闻视频2:https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209104902N3v5Vpxuvb.mp4
M3U8 格式
- 西瓜播放器 Demo:https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8
- 大白兔:https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8
MP3 音频文件
- https://sample.cat/zh/mp3
音视频裁剪
- https://online-video-cutter.com/projects/e0aea4ad-e898-429c-854e-07f45eb273ae









