我正在尝试为我的网站构建一个音频播放器。我在网上找到了一个教程,但是在我们的网站上它可以工作但是当我尝试将它用于我的时候,却没有。我已经到了我刚刚从演示站点复制代码的地步,它仍然无法正常工作。请帮助我。
List
var songs = ["https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3", "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3"];
var songTitle = document.getElementById('songTitle');
var songSlider = document.getElementById('songSlider');
var currentTime = document.getElementById('currentTime');
var duration = document.getElementById('duration');
var volumeSlider = document.getElementById('volumeSlider');
var nextSongTitle = document.getElementById('nextSongTitle');
var song = new Audio();
var currentSong = 0;
window.onload = loadSong;
function loadSong() {
song.src = songs[currentSong];
songTitle.textContent = (currentSong + 1) + ". " + songs[currentSong];
nextSongTitle.innerHTML = "<b>Next Song: </b>" + songs[currentSong + 1 % songs.length];
song.playbackRate = 1;
song.volume = volumeSlider.value;
song.play();
setTimeout(showDuration, 1000);
}
setInterval(updateSongSlider, 1000);
function updateSongSlider() {
var c = Math.round(song.currentTime);
songSlider.value = c;
currentTime.textContent = convertTime(c);
if (song.ended) {
next();
}
}
function convertTime(secs) {
var min = Math.floor(secs / 60);
var sec = secs % 60;
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
return (min + ":" + sec);
}
function showDuration() {
var d = Math.floor(song.duration);
songSlider.setAttribute("max", d);
duration.textContent = convertTime(d);
}
function playOrPauseSong(img) {
song.playbackRate = 1;
if (song.paused) {
song.play();
img.src = "images/pause.png";
} else {
song.pause();
img.src = "images/play.png";
}
}
function next() {
currentSong = currentSong + 1 % songs.length;
loadSong();
}
function previous() {
currentSong--;
currentSong = (currentSong < 0) ? songs.length - 1 : currentSong;
loadSong();
}
function seekSong() {
song.currentTime = songSlider.value;
currentTime.textContent = convertTime(song.currentTime);
}
function adjustVolume() {
song.volume = volumeSlider.value;
}
function increasePlaybackRate() {
songs.playbackRate += 0.5;
}
function decreasePlaybackRate() {
songs.playbackRate -= 0.5;
}
答案 0 :(得分:0)
我的猜测是你在HTML之前运行JS代码。因此,在DOM中存在之前选择volumeSlider。只需在结束前运行脚本,它应该没问题。
而不是这样做:
<head>
<script>
document.getElementById('volumeSlider') // <-- won't find the element (null)
</script>
</head>
<body>
<input id="volumeSlider" />
</body>
这样做:
<head>
</head>
<body>
<input id="volumeSlider" />
<script>
document.getElementById('volumeSlider') // <-- Will find the element because it's created before
</script>
</body>