```This will create an"/> ```This will create an">

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

How to add background music lyrics with javascript

WBOY
WBOYOriginal
2023-05-09 19:23:071192browse

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>

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>

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:

<button id="play">播放</button>
<button id="pause">暂停</button>
<button id="stop">停止</button>
<input type="range" id="volume" min="0" max="100" value="50">

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]第四句歌词

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: "第一句歌词" },
  { time: 5, text: "第二句歌词" },
  { time: 10, text: "第三句歌词" },
  { time: 15, text: "第四句歌词" }
];

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:

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

<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>

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:

<div id="lyrics"></div>

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:
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