Reputation: 2862
I have a simple jquery based MP3 player. To control audio I have this code:
<input type="range" min="0" max="1" step="0.1"/>
$(document).ready(function() {
$(".audio-clip input[type='range']").on("input", function() {
$(this).parent("div").find("audio")[0].volume = this.value;
});
});
I wonder how can I do the same but for controlling the audio position with a range
element in an MP3 song?
Upvotes: 1
Views: 146
Reputation: 337560
Assuming you cannot use the standard controls
attribute to handle volume and scanning through the file, you can use similar logic to what you have already implemented for volume to control the position in the file.
You can use a range
element with values from 0
to 100
then set the currentTime
of the audio, based on the value as a percentage. Also note that you can use the timeUpdate
event to move the range slider along as the file plays. Try this:
<div class="audio-clip">
<audio id="audio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto"></audio>
<label>
Volume:
<input type="range" class="volume" min="0" max="1" step="0.1" value="1" />
</label>
<label>
Position:
<input type="range" class="position" min="0" max="100" step="1" value="0" />
</label>
</div>
$(".audio-clip .volume").on("input", function() {
var audio = $(this).closest("div").find("audio")[0];
audio.volume = this.value;
});
$('.audio-clip .position').on('input', function() {
var audio = $(this).closest("div").find("audio")[0];
audio.currentTime = (audio.duration / 100) * this.value;
});
$('audio').on('timeupdate', function() {
var pc = (audio.currentTime / audio.duration) * 100;
$(this).closest('div').find('.position').val(pc);
})
Note that the example won't work in a snippet due to the cross-domain audio source, however it does work in a fiddle as you can see in the link below:
Upvotes: 1