const fs = require('fs')
const path = require('path')
//声明getTime函数,查找关键字,并计算时长
function getTime(buffer) {
let start
if (buffer.indexOf(Buffer.from('mvhd')) != -1) {
start = buffer.indexOf(Buffer.from('mvhd'))
} else {
return false
}
const timeScale = buffer.readUInt32BE(start + 16)
const duration = buffer.readUInt32BE(start + 20)
console.log('timeScale', timeScale, 'duration', 1)
const movieLength = Math.floor(duration / timeScale)
if (movieLength === 0) {
return false
}
return movieLength
}
//声明read()函数,打开文件
async function read(file) {
//使用read() 先返回一个promise
return new Promise((resolve, reject) => {
fs.open(file, 'r', (err, fd) => {
if (err) {
reject(err)
} else {
resolve(fd)
}
})
})
}
//声明readfile函数,读数据
async function readfile(fd, buff, start_position) {
return new Promise((resolve, reject) => {
fs.read(
fd,
buff,
0,
10000,
start_position,
function (err, bytesRead, buffer) {
if (err) {
reject(err)
} else {
resolve(buffer)
}
}
)
})
}
//声明主函数
let getVideoTime = async function (file) {
//声明这个函数中有异步操作,read()会先收到一个promise
let start_position = 0
const buff = Buffer.alloc(10000)
let fd = await read(file)
for (i = 0; i < 1000000; i++) {
let buff_data = await readfile(fd, buff, start_position)
const time = getTime(buff_data)
console.log('time', time)
if (time) {
return time
} else {
start_position = start_position + 9900
}
}
}
//const dir_path = 'D:/工作/课程/yuying/grade1/chinese1 - 副本';
const dir_path = '/temp/yuying'
// 用来存放所有需要判断时长的视频
const video_Array = []
// 判断文件信息
function files_stat(filepath) {
// 读取文件夹
const files = fs.readdirSync(filepath)
files.forEach((fileName) => {
// 获取文件的绝对路径
let filePath = path.join(filepath, fileName)
//根据文件路径获取文件信息
let stats = fs.statSync(filePath)
if (stats.isDirectory()) {
// 如果是文件夹,则递归
files_stat(filePath)
}
// 如果是文件且后缀是MP4 则推入到视频数组中
else if (stats.isFile() && /^.*\.mp4$/.test(fileName)) {
video_Array.push(filePath)
}
})
}
files_stat(dir_path)
// 判断时长时长
function getTotals(video_Array) {
let video_ArrayPromises = video_Array.map((video) => getVideoTime(video))
return Promise.all(video_ArrayPromises).then((video_time) => {
video_time.forEach((total_time, index) => {
total_time = Math.round(total_time)
const hours = parseInt(total_time / 3600)
const minutes = parseInt((total_time % 3600) / 60)
const seconds = (total_time % 3600) % 60
const timeStr = `${video_Array[index]},视频时长:${hours}小时${minutes}分钟${seconds}秒`
console.log(timeStr)
})
return video_time.reduce((ac, cv) => ac + cv)
})
}
const getVideoTotalTime = async () => {
await getTotals(video_Array).then((total_time) => {
// 四舍五入取整
total_time = Math.round(total_time)
const hours = parseInt(total_time / 3600)
const minutes = parseInt((total_time % 3600) / 60)
const seconds = (total_time % 3600) % 60
const timeStr = `视频总时长:${hours}小时${minutes}分钟${seconds}秒`
console.log(timeStr)
})
}
使用node.js 遍历判断本地文件夹内所有视频的总时长
猜你喜欢
转载自blog.csdn.net/xutongbao/article/details/126225871
今日推荐
周排行