- Определите массив объектов песни, где каждый объект содержит информацию о песне, такую как ее название, исполнитель, альбом и путь к файлу.
- Создайте функцию, которая инициализирует музыкальный проигрыватель, настроив необходимые элементы HTML и прослушиватели событий. Эта функция также должна загружать первую песню в массиве и отображать информацию о ней в плеере.
- Создайте функции для управления воспроизведением, приостановкой и пропуском дорожек. Эти функции должны обновлять элементы HTML, чтобы отображать текущую песню, а также воспроизводить или приостанавливать аудиофайл.
- Создайте функции для обработки индикатора выполнения и отображения текущего времени. Эти функции должны обновлять индикатор выполнения и текущее время во время воспроизведения песни.
- Создайте функции для обработки взаимодействия пользователя с музыкальным проигрывателем, например нажатия кнопки воспроизведения/паузы или нажатия песни в списке воспроизведения.
- Добавьте стиль, чтобы музыкальный проигрыватель выглядел визуально привлекательным и удобным для пользователя.
HTML
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Music Player</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Music Player</h1> <audio id="audio-player"></audio> <div id="song-info"> <h2 id="song-title"></h2> <h3 id="song-artist"></h3> <h3 id="song-album"></h3> </div> <div id="player-controls"> <button id="play-pause-btn"><i class="fas fa-play"></i></button> <button id="skip-back-btn"><i class="fas fa-backward"></i></button> <button id="skip-forward-btn"><i class="fas fa-forward"></i></button> <div id="time-info"> <span id="current-time">0:00</span> <span>/</span> <span id="duration">0:00</span> </div> <div id="progress-bar-container"> <div id="progress-bar"></div> </div> </div> <ul id="song-list"></ul> <script src="app.js"></script> </body> </html>
CSS
/* Add CSS styling for the Music Player interface */ body { background-color: #333; color: #fff; font-family: sans-serif; margin: 0; padding: 0; } h1, h2, h3 { margin: 0; padding: 10px; } #audio-player { display: none; } #song-info { text-align: center; } #player-controls { align-items: center; display: flex; justify-content: center; margin: 20px 0; } #player-controls button { background-color: transparent; border: none; cursor: pointer; font-size: 1.5em; margin: 0 10px; outline: none; } #player-controls button i { color: white; } #time-info { color: white; font-size: 0.8em; margin: 0 10px; }
Если вы хотите получить остальную часть кода css, нажмите здесь.
JavaScript
// Define the audio player and song list variables const audioPlayer = document.getElementById("audio-player"); const songList = document.getElementById("song-list"); // Define the current song and index variables let currentSong = null; let currentIndex = 0; // Define the play button variable and add an event listener to it const playButton = document.getElementById("play"); playButton.addEventListener("click", togglePlay); // Define the previous and next button variables and add event listeners to them const prevButton = document.getElementById("prev"); prevButton.addEventListener("click", playPrevSong); const nextButton = document.getElementById("next"); nextButton.addEventListener("click", playNextSong); // Define the progress bar and time info variables const progressBar = document.getElementById("progress-bar"); const timeInfo = document.getElementById("time-info"); // Define the song list items and add event listeners to them const songItems = songList.getElementsByTagName("li"); for (let i = 0; i < songItems.length; i++) { songItems[i].addEventListener("click", function() { playSong(i); }); } // Initialize the audio player audioPlayer.src = songItems[0].getAttribute("data-src"); audioPlayer.load(); // Function to play a song function playSong(index) { // Set the current song and index variables currentSong = songItems[index]; currentIndex = index; // Update the song info display const songTitle = currentSong.getElementsByTagName("span")[0].textContent; const songArtist = currentSong.getElementsByTagName("span")[1].textContent; document.getElementById("song-title").textContent = songTitle; document.getElementById("song-artist").textContent = songArtist; // Update the active class on the song list items for (let i = 0; i < songItems.length; i++) { songItems[i].classList.remove("active"); } currentSong.classList.add("active"); // Load and play the selected song audioPlayer.src = currentSong.getAttribute("data-src"); audioPlayer.play(); // Update the play button icon playButton.innerHTML = "<i class='fas fa-pause'></i>"; } // Function to toggle the play/pause state of the audio player function togglePlay() { if (audioPlayer.paused) { audioPlayer.play(); playButton.innerHTML = "<i class='fas fa-pause'></i>"; } else { audioPlayer.pause(); playButton.innerHTML = "<i class='fas fa-play'></i>"; } } // Function to play the previous song function playPrevSong() { if (currentIndex === 0) { playSong(songItems.length - 1); } else { playSong(currentIndex - 1); } } // Function to play the next song function playNextSong() { if (currentIndex === songItems.length - 1) { playSong(0); } else { playSong(currentIndex + 1); } } // Event listener to update the progress bar and time info as the song plays audioPlayer.addEventListener("timeupdate", function() { const duration = audioPlayer.duration; const currentTime = audioPlayer.currentTime; const progress = (currentTime / duration) * 100; progressBar.style.width = progress + "%"; timeInfo.textContent = formatTime(currentTime) + " / " + formatTime(duration); }); // Function to format the time in minutes and seconds function formatTime(time) { const minutes = Math.floor(time / 60); const seconds = Math.floor(time % 60); return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`; } // Function to initialize the music player function initializePlayer() { // Get references to the DOM elements const audioElement = document.getElementById("audio"); const playButton = document.getElementById("play-button"); const pauseButton = document.getElementById("pause-button"); const nextButton = document.getElementById("next-button"); const previousButton = document.getElementById("previous-button"); const progressBar = document.getElementById("progress-bar"); const currentTime = document.getElementById("current-time"); const totalTime = document.getElementById("total-time");
Для получения остальной части кода нажмите здесь.
Узнать больше
- Расширенный проект Python: чат-бот с использованием НЛП
- Система рекомендаций фильмов с использованием совместной фильтрации
- коды игр на питоне
- Начинающий проект Python: Калькулятор
- Идеи проекта Javascript api: Приложение Weather
- Для других javascript-проектов
Больше информации о нас
Facebook: Нажмите
Телеграм-группа упражнений: Клик
Ютуб: Нажми