Building a Music Player Application with Kendo UI and jQuery

栏目: IT技术 · 发布时间: 4年前

内容简介:In this tutorial, we build a music player using jQuery and Kendo UI’s component for notifications. The player will pause and play songs, and deliver notifications based on the song playing.Music players are everywhere these days. On our phones, on websites

In this tutorial, we build a music player using jQuery and Kendo UI’s component for notifications. The player will pause and play songs, and deliver notifications based on the song playing.

Music players are everywhere these days. On our phones, on websites, and on computers. The most popular way to distribute music is through the internet. Over the years many applications have sprung up giving us the ability to stream, download or buy music from the comfort of our beds.

Kendo UI is a set of tools and components created to help reduce the amount of code necessary to perform certain UI tasks.

In this tutorial we attempt to create a basic music player with jQuery while utilizing one of Kendo UI’s handy components.

Prerequisites

To follow this tutorial, a basic understanding of jQuery and JavaScript is required. HTML/CSS knowledge is also recommended but not mandatory.

To build the application, here are a few tools we’ll use:

Building a Music Player Application with Kendo UI and jQuery

Initializing the Application

Our goal is to have a working music player where music can be played from. We will go through the steps necessary to create one with HTML/CSS and jQuery.

Create a folder called musicplayer and define this folder structure inside it:

musicplayer/
          css/
           player.css
          js/
           player.js
          index.html

Let’s start adding data and functionality to our application.

Open your index.html file and add the following lines of code to it:

<!-- ./index.html -->
    <!Doctype html>
     <html>
        <head> 
            <!-- Section one -->
            <title>Music Player</title>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"/>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"/>
            <link rel="stylesheet" href="css/player.css"/>
        </head>
      <body>
               <!-- Section two -->
                   <div>
                     <div></div>

                    <div>
                      <span></span>
                      <span> - </span>
                      <span></span>
                    </div>

                    <div>
                      <div>
                        <i></i>
                      </div>
                      <div>
                        <i></i>
                      </div>
                      <div>
                        <i></i>
                      </div>

                      <div>
                        <i></i>
                      </div>
                    </div>

                    <div>
                      <i></i>
                      <div></div>
                    </div>

                    <div></div>
                  </div>
               <!-- Section three -->
                  <ul id="playlist">
                    <li audioURL="https://res.cloudinary.com/daintu6ky/video/upload/v1553018255/A_Chase.mp3" artist="Artist 1">Track 1</li>
                    <li audioURL="https://res.cloudinary.com/daintu6ky/video/upload/v1553018255/A_Chase.mp3" artist="Artist 2">Track 2</li>
                    <li audioURL="http://picdn.net/shutterstock/audio/397292/preview/preview.mp3https://res.cloudinary.com/daintu6ky/video/upload/v1553018255/A_Chase.mp3" artist="Artist 3">Track 3</li>
                    <li audioURL="https://res.cloudinary.com/daintu6ky/video/upload/v1553018255/A_Chase.mp3" artist="Artist 4">Track 4</li>
                  </ul>
              <!-- Section four -->
              <script src="https://code.jquery.com/jquery-3.3.1.js"
              integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
              crossorigin="anonymous">
              </script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
              <script src="js/player.js"></script>
        </body>
    </html>

In our index.html file we have four sections. Let’s briefly discuss their usage:

  • Section One: Here we import the libraries that will be required for our app.
  • Section Two: We define the HTML tags necessary to control sections of the player body. We will display the artist’s name and the song title, display some buttons and a tracker for our player.
  • Section Three: We define our list of songs. When we add our JavaScript functions, we will see how to dynamically pass the values to the tags created above.
  • Section Four : We import our JavaScript file and the libraries needed for our app.

To visualize our screen we need some css styles. Let’s add them. Open up your player.css file and add the following to it:

// js/player.css
    * {
      margin: 0;
      padding: 0;
    }
    body {
      background-color: #fff;
      font-family: 'lato', sans-serif !important;
    }
    .player {
      background: #242628;
      background: -moz-linear-gradient(top, #242628 0%, #000000 100%);
      background: -webkit-linear-gradient(top, #242628 0%, #000000 100%);
      background: linear-gradient(to bottom, #242628 0%, #000000 100%);
      filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#242628', endColorstr='#000000', GradientType=0);
      position: relative;
      width: 500px;
      margin: 0 auto;
      margin-top: 80px;
      z-index: 2;
    }
    .splitTxt,
    .icons {
      color: #ffffff;
    }
    .trackDetails {
      text-align: center;
      margin: 4px auto;
      width: 300px;
      height: 38px;
      border: 1px solid #1e1e1e;
      background: #000000;
      border-radius: 4px;
      padding: 6px;
    }
    .title,
    .artist {
      color: #999;
      left: 167px;
    }
    .title {
      font-size: 14px;
      font-weight: bold;
    }
    .artist {
      font-size: 12px;
    }

Here we add styles for our music player’s basic look. Since we want music control options in our application, let’s add some more styling for that. In the same file add the following lines of code:

.volumeIcon {
      position: absolute;
      right: 0;
      cursor: pointer;
      height: 34px;
      width: 32px;
    }
    .volumeIcon {
      bottom: 6px;
      display: block;
    }
    .controls {
      cursor: pointer;
      height: 40px;
      width: 120px;
      margin: 0 auto;
    }
    .controls .play,
    .controls .pause,
    .controls .rew,
    .controls .fwd {
      float: left;
      height: 40px;
      width: 40px;
      line-height: 40px;
      text-align: center;
    }
    .controls .play,
    .controls .pause,
    .plIcon,
    .volumeIcon {
      font-size: 26px;
    }
    .controls .pause {
      display: none;
    }
    .hidden {
      display: none;
    }
    .controls .visible {
      display: inline-block;
    }
    .tracker {
      cursor: pointer;
      height: 5px;
    }
    .ui-widget.ui-widget-content {
      border: 0;
    }
    .ui-corner-all {
      border-radius: 0;
    }
    .ui-slider .ui-slider-handle {
      display: block;
      height: 14px;
      border-radius: 14px;
      width: 14px;
      -webkit-transition: all ease-in-out .3s;
      transition: all ease-in-out .3s;
    }
    .tracker .ui-slider-range {
      background: #00dbde;
      background: -moz-linear-gradient(left, #00dbde 0%, #fc00ff 100%);
      background: -webkit-linear-gradient(left, #00dbde 0%, #fc00ff 100%);
      background: linear-gradient(to right, #00dbde 0%, #fc00ff 100%);
      filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#00dbde', endColorstr='#fc00ff', GradientType=1);
      -webkit-transition: all ease-in-out .3s;
      transition: all ease-in-out .3s;
      height: 100%;
      top: 0;
    }
    .volume .ui-slider-range {
      background: #333333;
      -webkit-transition: all ease-in-out .3s;
      transition: all ease-in-out .3s;
    }
    .volume.ui-widget-content {
      background: #00dbde;
    }
    .ui-slider-handle {
      cursor: pointer;
      height: 10px;
      margin-left: -5px;
      top: 2px;
      width: 10px;
      z-index: 2;
    }
    .volume {
      display: none;
      right: 12px;
      position: absolute;
      top: 35px;
      height: 100px;
      width: 20px;
      box-shadow: 0px 0px 10px #000;
    }
    .volume .ui-slider-handle {
      display: none;
    }
    .playlist {
      background-color: #1e1e1e;
      list-style-type: none;
      padding-bottom: 10px;
      padding: 15px;
      position: relative;
      width: 100%;
      z-index: 1;
      display: none;
      -webkit-transition: all ease-in-out .1s;
      transition: all ease-in-out .1s;
    }
    .playlist li {
      color: #eeeeee;
      cursor: pointer;
      margin-bottom: 4px;
      padding: 6px 12px;
      -webkit-transition: all ease-in-out .1s;
      transition: all ease-in-out .1s;
    }
    .playlist li:hover {
      background: #333333;
    }
    .playlist li.active {
      font-weight: bold;
      background: #000000;
    }
    .show {
      display: block;
    }
    .ui-state-default,
    .ui-widget-content .ui-state-default,
    .ui-widget-header .ui-state-default,
    .ui-button,
    html .ui-button.ui-state-disabled:hover,
    html .ui-button.ui-state-disabled:active {
      border: 0;
    }
    .ui-widget-content {
      background: #666666;
    }

Now when you open up your index.html file you will see this:

Building a Music Player Application with Kendo UI and jQuery

We have our basic screen up. Next, we need to add some interaction.

Writing Our Music Player Function

We will use a mix of JavaScript and jQuery to add functionality to our UI to make it work as expected. Now open up your player.js file and add the following code to it:

// js/player.js
    function init(){
       var song;
       var tracker = $('.tracker');
       var volume = $('.volume');

      function initAudio(elem) {
        var url = elem.attr('audiourl');

        var title = elem.text();
        var artist = elem.attr('artist');

        $('.player .title').text(title);
        $('.player .artist').text(artist);

        // song = new Audio('media/'+url);
        song = new Audio(url);

        // timeupdate event listener
        song.addEventListener('timeupdate', function() {
          var curtime = parseInt(song.currentTime, 10);
          tracker.slider('value', curtime);
        });

        $('.playlist li').removeClass('active');
        elem.addClass('active');
      }

      function playAudio() {
        song.play();

        tracker.slider("option", "max", song.duration);

        $('.play').addClass('hidden');
        $('.pause').addClass('visible');
      }

      function stopAudio() {
        song.pause();

        $('.play').removeClass('hidden');
        $('.pause').removeClass('visible');
      }

      // play click
      $('.play').click(function(e) {
        e.preventDefault();
        // playAudio();

        song.addEventListener('ended', function() {
          var next = $('.playlist li.active').next();
          if (next.length == 0) {
            next = $('.playlist li:first-child');
          }
          initAudio(next);

          song.addEventListener('loadedmetadata', function() {
            playAudio();
          });

        }, false);

        tracker.slider("option", "max", song.duration);
        song.play();
        $('.play').addClass('hidden');
        $('.pause').addClass('visible');

      });

      // pause click
      $('.pause').click(function(e) {
        e.preventDefault();
        stopAudio();
      });

      // next track
      $('.fwd').click(function(e) {
        e.preventDefault();

        stopAudio();

        var next = $('.playlist li.active').next();
        if (next.length === 0) {
          next = $('.playlist li:first-child');
        }
        initAudio(next);
        song.addEventListener('loadedmetadata', function() {
          playAudio();
        });
      });

      // prev track
      $('.rew').click(function(e) {
        e.preventDefault();

        stopAudio();

        var prev = $('.playlist li.active').prev();
        if (prev.length === 0) {
          prev = $('.playlist li:last-child');
        }
        initAudio(prev);
        song.addEventListener('loadedmetadata', function() {
          playAudio();
        });
      });

      // playlist elements - click
      $('.playlist li').click(function() {
        stopAudio();
        initAudio($(this));
      });

      // initialization - first element in playlist
      initAudio($('.playlist li:first-child'));

      song.volume = 0.8;

      volume.slider({
        orientation: 'vertical',
        range: 'max',
        max: 100,
        min: 1,
        value: 80,
        start: function(event, ui) {},
        slide: function(event, ui) {
          song.volume = ui.value / 100;
        },
        stop: function(event, ui) {},
      });

      $('.volumeIcon').click(function(e) {
        e.preventDefault();
        $('.volume').toggleClass('show');
      });

      // empty tracker slider
      tracker.slider({
        range: 'min',
        min: 0,
        max: 10,
        start: function(event, ui) {},
        slide: function(event, ui) {
          song.currentTime = ui.value;
        },
        stop: function(event, ui) {}
      });

    }
    $(init);

Let’s go over some defined functions:

  • First we define wrapper function (init) to house all other variables, events and functions. It is initialized at the end of the file.
  • We declare variables to reference the player controllers in our HTML file.
  • Next we define a function to initialize and play our audio file by passing a value to it.
  • We then add an event listener at the end of the function to listen for when our tracker is clicked or changed in position.
  • Next we define a play function. This will be triggered anytime the play button is clicked.
  • Next we define a stop function. This will be triggered anytime the pause button is clicked.
  • The functions that follow define what happens when the play, pause, next and previous buttons are clicked.
  • The last two functions define the actions for when the button for volume or the music tracker is clicked.

Adding Notifications to Our Player Using Kendo UI

We want to receive a notification whenever our song is changed. To do that, we will use Kendo UI’s notification component. We will need to add some code to both our HTML and JavaScript file for it to work.

Open up your index.html file and add the following code to our first and fourth section.

<!-- ./index.html -->

    <!-- other code stays same -->

     <head>
              <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.220/styles/kendo.common.min.css">
              <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.220/styles/kendo.rtl.min.css">
              <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.220/styles/kendo.default.min.css">
              <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.1.220/styles/kendo.mobile.all.min.css">
              <script src="https://kendo.cdn.telerik.com/2019.1.220/js/kendo.all.min.js">           </script>
     </head>

        <!-- add id in bold to the play class button -->
         <div>
            <div id="showPopupNotification">
              <i></i>
            </div>
         </div>

       <span id="popupNotification"></span>
       <!-- the end of the closing div -->                
    <!-- other code stays same -->

Here, we import all our files needed for Kendo UI to work. Then we update parts of our HTML to enable display. Since we want a notification to happen when the play button is clicked, we give it an **id** so we can reference it in our JavaScript file. Finally we add a span to display the notification.

Add this code to the player.js file:

// js/player.js

    // add this inside the initAudio function after declare title variable.
     var popupNotification = $("#popupNotification").kendoNotification().data("kendoNotification");
      $("#showPopupNotification").click(function(){             
           popupNotification.show("You are playing "+ title);
       });

Now whenever you click the play button you will get a notification on what song you are playing.

Building a Music Player Application with Kendo UI and jQuery

Conclusion

In this tutorial we learned how to use jQuery, HTML and CSS to build a music player. The knowledge from here can help you create more real-time apps. Be sure to post comments for clarity on parts you don’t understand. Happy coding.


以上所述就是小编给大家介绍的《Building a Music Player Application with Kendo UI and jQuery》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

金融数量分析

金融数量分析

郑志勇 / 北京航空航天大学出版社 / 2014-7-1 / CNY 58.00

《金融数量分析——基于MATLAB编程(第3版)》一书中的案例均来源于作者的工作实际,并充分体现“案例的实用性、程序的可模仿性”,程序中附有详细的注释。例如,投资组合管理、KMV模型计算、期权定价模型与数值方法、风险价值VaR的计算等案例程序,读者可以直接使用或根据需要在源代码的基础上修改、完善。 本书共23章。前两章分别对金融市场的基本概况与MATLAB的基础知识进行概述;接下来为20个金......一起来看看 《金融数量分析》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具