更新 我使用以下代码修复了它!
const songPick = document.querySelector("select");
const toggle = document.querySelector(".toggle");
const audio = document.querySelector('audio[src="Kalliope.mp3"]');
toggle.addEventListener("click", pauseOrPlay);
songPick.addEventListener("change", audioSource);
function audioSource() {
audio.src = songPick.value;
}
function pauseOrPlay() {
if(!audio.paused && !audio.ended) {
audio.pause();
toggle.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
}else{
audio.play();
toggle.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
}
}
我试图制作一个定制的音频播放器。当我暂停并播放音乐时,我有一个问题,它在我暂停音频之前不会回到当前时间,而是从头开始播放。当我使用一个源但我有多个音频源时,我可以使它工作。
<article class="music__player">
<p>Välj en sång</p>
<select name="Song pick">
<option value="Kalliope.mp3" selected>Kalliope</option>
<option value="Unknown Planet.mp3">Unknown Planet</option>
<option value="Space Loop.wav">Space Loop</option>
<option value="Autumn Nights.mp3">Autumn Nights</option>
</select>
<img src="space-160x160.jpg" alt="Kalliope Image">
<div class="played__time"></div>
<audio src=""></audio>
<div class="audio-controls">
<button class="audio__button toggle" title="Play Audio" >
<i class="fa fa-play" aria-hidden="true"></i>
</button>
<button class="audio__button stop" title="Stop Audio">
<i class="fa fa-stop" aria-hidden="true"></i>
</button>
<button class="audio__button" title="Step Forward" data-skip="10">
<i class="fa fa-step-forward" aria-hidden="true"></i>
</button>
<button class="audio__button" title="Step Backwards" data-skip="-10">
<i class="fa fa-step-backward" aria-hidden="true"></i>
</button>
</div>
</article>
const songPick = document.querySelector("select");
const toggle = document.querySelector(".toggle");
const audio = document.querySelector('audio[src=""]');
toggle.addEventListener("click", pauseOrPlay);
let audioTime;
function pauseOrPlay() {
if(!audio.paused && !audio.ended) {
audio.src = songPick.value;
audio.pause();
toggle.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
}else{
if(audioTime > 0)
{
audio.currentTime = audioTime;
}
audio.src = songPick.value;
audio.play();
toggle.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
}
}
audio.addEventListener("timechange", function () {
audioTime = audio.currentTime;
});