In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use JavaScript to achieve web player". In daily operation, I believe many people have doubts about how to use JavaScript to achieve web player. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use JavaScript to achieve web player". Next, please follow the editor to study!
Here is a picture of a player I made.
First of all, let's look at the player from top to bottom, and the top of it is the title (head): my music; in the middle is the content (body): song; and the bottom (foot): the control that controls music playback. In the title section, there is only the title: my music, while the middle part is the playlist, and each song has a playback icon (available only when the music is played) and song information. at the bottom there are some icons that control playback, the name of the song currently being played, the progress of the song, and the duration of the song.
Layout we want to save the structure and style separation, the structure is written in HTML, the style is written in CSS.
Page structure layout: my songs are not written directly, they are loaded with json objects. So the content part of the song I wrote here is just a format. The icon of the previous song / play, pause / next song, I wrote with the a tag, and the icon was added to the background of the a tag. I realized the progress of the song with two div, in which a div shows gray as the total progress, and the above div shows white as the current progress of the song.
Title, my music.
Palms of the hand-- Dingdang 0.00 my music 4.13
Page style layout: you can set your own good-looking fonts and color styles. In addition, when setting background: url (".. / imgs/play-default.png") no-repeat;, note: the path inside url should write two dots to indicate exit from the current directory and go to the root directory. There is also a background to set no-repeat (non-tiling). When using absolute positioning, you should follow the principle of absolute paternity and also pay attention to setting the z-index property.
/ * remove the inner and outer margins in the tag * / * {margin: 0; padding: 0;} / * set the entire player style: layout is elastic box, horizontal center, width and height, with frame, set elastic direction of elastic box: column (vertical vertical) * / .music-list {display: flex; margin: 0 auto; height: 600px; width: 400px; border: 1px solid # ccc Flex-direction: column;} / * set title section * / .head {flex: 1; background: # 3498db; color: # fff; font: 24px "Chinese script"; display: flex; / * horizontal axis centered * / justify-content: center; / * vertical axis centered * / align-items: center; border-bottom: 1px solid white; box-sizing: border-box } / * set content part * / .body {flex: 7; / * hide the excess part * / overflow-x: hidden;} / * set the bottom part * / .foot {flex: 2; display: flex; background: # 3498db; color: # fff; font-size: 14px; border-top: 1px solid white; box-sizing: border-box } / * format each song * / .item {display: flex; height: 50px; line-height: 50px; background: # 3498db; color: # fff; font-size: 14px; cursor: pointer; transition: all .5s;} / * all songs except the last song show the bottom frame * / .item:not (: last-child) {border-bottom: 1px solid white } / * set the background color of the small icon when the song is played * / .box11 {background: # f0f0f0;} / * set the song information * / .item-name {flex: 6; / * do not write * / padding: 010px;} / * the effect of mouse hover * / .item:hover {background: # 2980b9 } / * effect of mouse click * / .item:active {/ * if you want a stereoscopic effect on a click event, you can add box shadow to the relative positioning * / position: relative; top: 2px; left: 2px; box-shadow: 5px 5px 10px rgba (0,0,0, .5);} / * set the occupation size of the icon of the previous song / playback, pause / next song * / .box1 {flex: 3; display: inline-block } / * set the occupation size of the current time of song playback * / .box2 {flex: 1; display: inline-block; padding: 50px 0; text-align: left;} / * set the progress of song playback and the occupation size of song names * / .box3 {flex: 5; display: inline-block; position: relative; padding: 35px 0 } / * set the total time occupied for song playback * / .box4 {flex: 1; display: inline-block; padding: 50px 0; text-align: right;} / * assign the icon size of the previous / playback, pause / next song * / .box1 a {display: inline-block; margin: 50px 0; width: 30%; height: 50% } / * set the icon of the previous song * / .btn-pre {background: url (".. / imgs/pre-default.png") no-repeat; cursor: pointer;} / * set the icon mouse hover effect of the previous song * / .btn-pre:hover {background: url (".. / imgs/pre-active.png") no-repeat } / * set the playback icon * / .btn-play {background: url (".. / imgs/play-default.png") no-repeat; cursor: pointer;} / * set the mouse hover effect of the playback icon * / .btn-play:hover {background: url (".. / imgs/play-active.png") no-repeat } / * set paused icon * / .btn-pause {background: url (".. / imgs/pause-default.png") no-repeat; cursor: pointer;} / * set paused icon hover effect * / .btn-pause:hover {background: url (".. / imgs/pause-active.png") no-repeat } / * set the icon of the next song * / .btn-next {background: url (".. / imgs/next-default.png") no-repeat; cursor: pointer;} / * set the icon mouse hover effect of the next song * / .btn-next:hover {background: url (".. / imgs/next-active.png") no-repeat;} / * set the font of the song name * / .m-name {font: 20px "italics" } / * set the overall progress of song playback * / .box31 {position: absolute; width: 100%; height: 2px; background: # cacaca; z-index: 1;} / * set the current progress of song playback * / .box32 {position: absolute; width: 20%; height: 2px; background: white; z-index: 2 } / * small dots moving along with the current progress of song playback * / .dot {position: absolute; display: inline-block; right: 0; top:-2px; height: 5px; width: 5px; border-radius: 2.5px; background: # fff;}
JavaScript code: because the play icon and pause icon click to change alternately, and these icons are displayed as the background, we can just change the background of the a tag, that is, change the background when you click (the way to change the background is to change the class). When setting the progress of song playback, you can take a look at some events in audio loadeddata, timeupdate, ended; can be realized with ended: the function of automatically playing the next song. When setting up the forward and backward functions, be careful to get the location of the mouse click (that is, the distance from the beginning). You can change the progress of the song by setting a value for player.currentTime.
/ / create a player dom object var player = document.createElement ('audio'); / / set a value to save the index of the currently played song var currentIndex = 0 Bash / set a flag to determine whether the song plays var isPlay = false;// dynamically loaded songs (function () {/ / set a value to save all songs dom object var html =''; / / get the dom object for of all songs (var I = 0) I
< musics.length; i++) { var m = musics[i]; //设置每一首歌曲的格式 html += ` ${m.name}---${m.artist} ` } //添加所有歌曲 document.getElementById('tbody')[xss_clean] = html; //给播放器一个默认的播放地址 player.src = musics[currentIndex].path;})();//为每一首歌曲设置点击事件var trs = document.querySelectorAll('.item')for (let i = 0; i < trs.length; i++) { trs[i].addEventListener('click', function () { //清除上一首歌曲的播放状态 clearStatus(); //获取歌曲索引 var index = this.dataset.index; currentIndex = index; var msc = musics[index]; //给播放器设置的播放地址 player.src = msc.path; //开始播放 startPlayer(); })}//函数:开始播放function startPlayer() { //设置播放标记 isPlay = true; // 播放歌曲 player.play(); trs[currentIndex].style.background = '#2980b9'; // 添加播放歌曲的小图标 trs[currentIndex].querySelector('.item-logo')[xss_clean] = ''; / / set the icon to the playback status document.querySelector (' # btnPlay'). ClassName = 'btn-pause'; / / set the song name document.querySelector (' # playingNmae'). InnerText = `${musics [currentIndex] .name}-${musics [currentIndex] .songs}`;} / / function: clear the playback status of the previous song function clearStatus () {trs [currentIndex] .style.background ='' Trs [currentIndex] .querySelector ('. Item-logo') [xss_clean] =';} / function: pause playback function pausePlay () {/ / pause playback player.pause (); / / set playback flag isPlay = false; / / set icon to paused state document.getElementById ('btnPlay'). ClassName =' btn-play' } / / function: click event document.querySelector ('.btn-pre'). AddEventListener (' click', function () {/ / pause pausePlay ()); / / clear the playback status of the previous song clearStatus (); / / implement the previous song function if (currentIndex = = 0) {currentIndex = musics.length-1;} else {--currentIndex } console.log (currentIndex) / / the playback address set to the player player.src = musics [currentIndex] .path; startPlayer ();}) / function: click event document.getElementById ('btnPlay'). AddEventListener (' click', function () {/ / judge the playback flag if (isPlay) {pausePlay ();} else {startPlayer () }}) / / function: click event document.querySelector ('.btn-next'). AddEventListener (' click', function () {pausePlay (); clearStatus (); if (currentIndex = = musics.length-1) {currentIndex = 0;} else {+ + currentIndex;} console.log (currentIndex) player.src = musics [currentIndex] .path; startPlayer () }) / / set the progress of song playback var now = 0 position var total = 0 role / event after the song data has been loaded player.addEventListener ('loadeddata', function () {/ / the current progress of the song (time) now = player.currentTime; / / the total progress of the song (time) total = player.duration / / display the progress (time) of the song to the player document.querySelector ('.play-current'). InnerText = fmtTime (now); document.querySelector (' .play-duration'). InnerText = fmtTime (total);}) / / when currentTime (current progress time of the song) is updated, the timeupdate event player.addEventListener ('timeupdate', function () {/ / get the current progress (time) of the song) now = player.currentTime / / the current progress of the song var p = now / total * 100 +'%'; / / synchronize the current progress of the song to the progress bar document.querySelector ('.box32'). Style.width = p; document.querySelector ('. Play-current'). InnerText = fmtTime (now) }) / / the song end event (the ability to automatically play the next song) player.addEventListener ('ended', function () {/ / clear the playback status of the previous song clearStatus (); / / play the next song currentIndex++; if (currentIndex > = musics.length) {currentIndex = 0;} player.src = musics[ currentIndex] .path; startPlayer () }) / / forward song event document.querySelector ('.box31'). AddEventListener ('click', function (e) {/ / get the location of the mouse click let right = e.offsetX; / / set the progress bar to the position of the mouse click document.querySelector (' .box32'). Style.width = right; / / calculate the progress of the song let seekTo = right/200*total / / set the progress of the song player.currentTime=seekTo;}) / / back the song event document.querySelector ('.box32'). AddEventListener ('click', function (e) {let left = e.offsetX; document.querySelector (' .box32'). Style.width = left; let seekTo = left/200*total; player.currentTime=seekTo;}) / / function: formatting time function fmtTime (time) {time * = 1000 Time = new Date (time); var m = time.getMinutes (); var s = time.getSeconds (); m = m < 10? 0' + m: M; s = s < 10? 0' + s: s; return m +':'+ s;}
Musics:
Var musics = [{artist: "GALA", id: 1, name: "chasing your Dream", path: "musics/1.mp3"}, {artist: "Chopsticks Brothers", id: 2, name: "Father", path: "musics/2.mp3"}, {artist: "Dingdang" Id: 3, name: "palm", path: "musics/3.mp3"}, {artist: "Sakuki plum", id: 4, name: "Good Night", path: "musics/4.mp3"}, {artist: "Zhang Shaohan", id: 5 Name: invisible Wings, path: "musics/5.mp3",}, {artist: "Rainie", id: 6, name: "Rain Love", path: "musics/6.mp3",}, {artist: "Yao Orchestra", id: 7, name: "Meteor" Path: "musics/7.mp3",}, {artist: "Escape Plan", id: 8, name: "re-Flight (MV version)", path: "musics/8.mp3",}, {artist: "Jin Guisheng", id: 9, name: "between Rainbows" Path: "musics/9.mp3",}]
At this point, the study on "how to use JavaScript to achieve a web player" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.