根据音质和时长计算音频文件大小,这种方法可能会存在误差,但本人测试有点误差也是在能接受的范围内。
首先需要获取文件的 时长 和 音质 (如:64、128、320)php代码
/**
* 根据音质和时长计算音频文件大小
*
* @param int $duration 时长(秒)
* @param int $sampleRate 采样率(Hz),如 44100(仅 WAV/FLAC 需要)
* @param int $bitDepth 位深(bit),如 16(仅 WAV/FLAC 需要)
* @param int $channels 声道数,如 2(仅 WAV/FLAC 需要)
* @param int $bitrate 比特率(kbps),如 128(仅 MP3/Ogg/M4A/AAC 需要)
* @param string $type 音频类型:'wav', 'flac', 'mp3', 'ogg', 'm4a', 'aac'
* @return float 返回文件大小(MB)
*/
function calculateAudioSize($duration, $sampleRate, $bitDepth, $channels, $bitrate, $type = 'mp3') {
$bytes = 0;
$type = strtolower($type);
if ($type === 'wav') {
$bytes = $sampleRate * $bitDepth * $channels * $duration / 8;
}
elseif ($type === 'flac') {
$rawBytes = $sampleRate * $bitDepth * $channels * $duration / 8;
$compressionRatio = 0.6;
$bytes = $rawBytes * $compressionRatio;
}
elseif (in_array($type, ['mp3', 'ogg', 'm4a', 'aac'])) {
$bytes = $bitrate * 1000 * $duration / 8;
}
return round($bytes / 1024 / 1024, 2);
}
调用示例
$duration = 180; // 3分钟 (180秒)
// 1. FLAC 文件:3分钟,CD音质 (44100Hz, 16bit, 2声道)
$flacSize = calculateAudioSize($duration, 44100, 16, 2, 0, 'flac');
echo "FLAC 文件大小约为:{$flacSize} MB\n";
// 2. AAC / M4A / Ogg 文件:3分钟,高音质 (256kbps)
$aacSize = calculateAudioSize($duration, 0, 0, 0, 256, 'aac');
echo "AAC/M4A/Ogg 文件大小约为:{$aacSize} MB\n";
]]>