Home Web Front-end Front-end Q&A How to add background music lyrics with javascript

How to add background music lyrics with javascript

May 09, 2023 pm 07:23 PM

Background music and lyrics are one of the commonly used elements in website design. They can make the website more attractive and personalized. In this article, we'll show you how to add background music and lyrics to your website via JavaScript.

  1. Add background music

In order to add background music, we need to create an HTML element to host the audio. An audio element can be created using the following code:

<audio id="audio" src="music.mp3"></audio>
Copy after login

This will create an audio element with the id "audio" and add the audio file "music.mp3" as its source.

Now we need to use JavaScript to control audio playback, pause, stop and volume control. We can create a JavaScript object called "audioPlayer" to handle these functions. The following is the complete code:

<audio id="audio" src="music.mp3"></audio>

<script>
  var audioPlayer = {
    audio: null,
    playButton: null,
    pauseButton: null,
    stopButton: null,
    volumeSlider: null,
    init: function() {
      this.audio = document.getElementById("audio");
      this.playButton = document.getElementById("play");
      this.pauseButton = document.getElementById("pause");
      this.stopButton = document.getElementById("stop");
      this.volumeSlider = document.getElementById("volume");

      this.bindEvents();
    },

    bindEvents: function() {
      var self = this;

      this.playButton.addEventListener("click", function() {
        self.audio.play();
      });

      this.pauseButton.addEventListener("click", function() {
        self.audio.pause();
      });

      this.stopButton.addEventListener("click", function() {
        self.audio.pause();
        self.audio.currentTime = 0;
      });

      this.volumeSlider.addEventListener("input", function() {
        self.audio.volume = self.volumeSlider.value / 100;
      });
    }
  };

  audioPlayer.init();
</script>
Copy after login

The above code creates an object named "audioPlayer", which includes play, pause, stop and volume control functions. To use this object, make sure you add the appropriate button and volume slider to your HTML:

&lt;button id=&quot;play&quot;&gt;播放&lt;/button&gt;
&lt;button id=&quot;pause&quot;&gt;暂停&lt;/button&gt;
&lt;button id=&quot;stop&quot;&gt;停止&lt;/button&gt;
&lt;input type=&quot;range&quot; id=&quot;volume&quot; min=&quot;0&quot; max=&quot;100&quot; value=&quot;50&quot;&gt;
Copy after login

Now, when the user clicks the play button, the audio will start playing; when the user clicks the pause button, the audio will be paused. ;When you click the Stop button, the audio will pause and return to the starting position; Use the volume slider to control the volume of the audio.

  1. Add background music lyrics

To add background music lyrics, you need to add the lyrics file to the website. Lyrics files usually exist in the form of text files, where each line contains the time and text of the lyrics. Here is an example of a simple lyrics file:

[00:00.00]歌名 - 歌手
[00:10.00]第一句歌词
[00:15.00]第二句歌词
[00:20.00]第三句歌词
[00:25.00]第四句歌词
Copy after login

In this example, the first line is the song information, enclosed in square brackets. Each subsequent line contains the time and text of the lyrics, with the time enclosed in square brackets expressed in minutes, seconds, and fractional seconds (mm:ss.xx).

In order to add lyrics to the website, we need to create an array called "lyrics" that contains the time and text of each line of lyrics. The following is a code example:

var lyrics = [
  { time: 0, text: &quot;第一句歌词&quot; },
  { time: 5, text: &quot;第二句歌词&quot; },
  { time: 10, text: &quot;第三句歌词&quot; },
  { time: 15, text: &quot;第四句歌词&quot; }
];
Copy after login

Now we need to create a JavaScript object named "lyricsDisplay" to set up the display and update of lyrics. The following is the complete code:

&lt;audio id=&quot;audio&quot; src=&quot;music.mp3&quot;&gt;&lt;/audio&gt;
&lt;div id=&quot;lyrics&quot;&gt;&lt;/div&gt;

<script>
  var audioPlayer = {
    // 略
  };

  var lyricsDisplay = {
    lyrics: null,
    display: null,
    activeLyric: -1,

    init: function(lyrics) {
      this.lyrics = lyrics;
      this.display = document.getElementById("lyrics");

      this.render();
      this.highlightLyric();
      this.bindEvents();
    },

    render: function() {
      var html = "";

      for (var i = 0; i < this.lyrics.length; i++) {
        html += "<div data-time='" + this.lyrics[i].time + "'>" + this.lyrics[i].text + "</div>";
      }

      this.display.innerHTML = html;
    },

    highlightLyric: function() {
      var self = this;

      var timer = setInterval(function() {
        self.activeLyric++;

        if (self.activeLyric == self.lyrics.length - 1) {
          clearInterval(timer);
        }

        for (var i = 0; i < self.lyrics.length; i++) {
          if (i === self.activeLyric) {
            self.display.children[i].className = "active";
          } else {
            self.display.children[i].className = "";
          }
        }

        var nextTime = self.lyrics[self.activeLyric + 1].time;
        var currentTime = audioPlayer.audio.currentTime;

        if (nextTime > currentTime) {
          break;
        }
      }, 100);
    },

    bindEvents: function() {
      var self = this;

      audioPlayer.audio.addEventListener("timeupdate", function() {
        self.highlightLyric();
      });
    }
  };

  var lyrics = [
    { time: 0, text: "第一句歌词" },
    { time: 5, text: "第二句歌词" },
    { time: 10, text: "第三句歌词" },
    { time: 15, text: "第四句歌词" }
  ];

  audioPlayer.init();
  lyricsDisplay.init(lyrics);
</script>
Copy after login

In the above code, we create an object named "lyricsDisplay", which includes the display and update functions of lyrics. To use this object, make sure you add a div with id = "lyrics" in your HTML:

&lt;div id=&quot;lyrics&quot;&gt;&lt;/div&gt;
Copy after login

Now when the user plays the audio, the lyrics will be highlighted at the correct time. We use the setInterval() method and the audio.currentTime property to update the active lyrics. Additionally, when the user clicks on the lyrics, the audio will jump to the corresponding time.

Conclusion

In this article we looked at how to add background music and lyrics to your website using JavaScript. To add background music, you first need to create an audio element and use JavaScript to control its play, pause, stop, and volume. To add lyrics, you need to add them to an array and use JavaScript to set up their display and update. By using these techniques, you can add some liveliness and personalization to your website.

The above is the detailed content of How to add background music lyrics with javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain the concept of lazy loading. Explain the concept of lazy loading. Mar 13, 2025 pm 07:47 PM

Explain the concept of lazy loading.

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

What is useEffect? How do you use it to perform side effects?

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

How does currying work in JavaScript, and what are its benefits?

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

How does the React reconciliation algorithm work?

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

What is useContext? How do you use it to share state between components?

What are the advantages and disadvantages of controlled and uncontrolled components? What are the advantages and disadvantages of controlled and uncontrolled components? Mar 19, 2025 pm 04:16 PM

What are the advantages and disadvantages of controlled and uncontrolled components?

Explain the purpose of each lifecycle method and its use case. Explain the purpose of each lifecycle method and its use case. Mar 19, 2025 pm 01:46 PM

Explain the purpose of each lifecycle method and its use case.

See all articles