Search code examples
phpxmltimerss

Convert XML RSS Feed Audio Length from Bytes to Minutes/Seconds in PHP


I am scraping an RSS Feed which includes <enclosure> elements for audio files. According to the spec, the length is given in bytes.

 <enclosure url="https://www.w3schools.com/media/audio-file.m4a" length="67960845" type="audio/x-m4a" />

I need to convert this length into an actual measurable time (i.e. hours, minutes, seconds). This would require knowing the bitrate (I believe), which I happen to have! The RSS feed comes from Anchor and according to Anchor, they sample their audio in stereo at 44.1 kHz, 128 kbit/s CBR.

I know the provided example length="67960845" converts to 71 minutes. I tried to reverse engineer it but I can't really find a good formula in order to reliably convert this like:

<?php 
    $length = 67960845;
    $seconds = $length / ????; 
?>

This request is in PHP but could apply to any language scraping an RSS feed.


Solution

  • If you convert the length to bits you can then divide it by the bitrate and then get the number of seconds:

    (67960845*8)/128/1000/60 = 70.792546875

    So...

    $length = 67960845;
    $bitrate_kbps = 128;
    $seconds = ceil(($length * 8) / $bitrate_kbps / 1000 / 60);
    

    Does this work for you?