Get audio file duration in jQuery code example
Example: Get audio file duration in jQuery
function analyize_mp3_add_meta_box() {
add_meta_box(
'analyize_mp3-analyize-mp3',
__( 'Analyize MP3', 'analyize_mp3' ),
'analyize_mp3_html',
'post',
'normal',
'default'
);
}
add_action( 'add_meta_boxes', 'analyize_mp3_add_meta_box' );
function analyize_mp3_html( $post) {
wp_nonce_field( '_analyize_mp3_nonce', 'analyize_mp3_nonce' ); ?>
<style type="text/css">
audio {display: none;}
</style>
<script type='text/javascript'><![CDATA[
jQuery(function(){
var objectUrl;
jQuery("#audio").on("canplaythrough", function(e){
var seconds = e.currentTarget.duration;
var duration = moment.duration(seconds, "seconds");
var time = "";
var hours = duration.hours();
if (hours > 0) { time = hours + ":" ; }
time = time + duration.minutes() + ":" + duration.seconds();
jQuery("#duration").text(time);
jQuery('#timelength').val(time);
URL.revokeObjectURL(objectUrl);
});
jQuery("#file").change(function(e){
var file = e.currentTarget.files[0];
jQuery("#filesize").text(file.size);
jQuery('#size').val(file.size);
objectUrl = URL.createObjectURL(file);
jQuery("#audio").prop("src", objectUrl);
});
});]]>
</script>
<input type="file" id="file" />
<audio id="audio"></audio>
<p>
<label>File Size:</label>
<span id="filesize"></span>
<input type="hidden" id="size" name="size" value=""/>
</p>
<p>
<label>Song Duration:</label>
<span id="duration"></span>
<input type="hidden" id="timelength" name="time" value=""/>
</p>
<?php }