HTML5+CSS3+JS realizes simple music playback

The following is a sample code of a simple HTML5+CSS3+JS music player implementation:

HTML part:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音乐播放器</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>音乐播放器</h1>
        <audio id="myAudio" controls>
            <source src="music.mp3" type="audio/mpeg">
        </audio>
        <button id="playButton">播放</button>
        <button id="pauseButton">暂停</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS part:

.container {
    
    
    text-align: center;
    margin-top: 10%;
}
h1 {
    
    
    font-size: 3em;
    margin-bottom: 30px;
}
button {
    
    
    margin-top: 20px;
    font-size: 1.5em;
}

JS part:

var myAudio = document.getElementById("myAudio");
var playButton = document.getElementById("playButton");
var pauseButton = document.getElementById("pauseButton");
playButton.addEventListener("click", function() {
    
    
    myAudio.play();
});
pauseButton.addEventListener("click", function() {
    
    
    myAudio.pause();
});

In the above code, we use HTML5 tags to embed music, and add two buttons to control music playback. Then, we simply beautified the page with CSS styles. Finally, we use JavaScript to listen for button click events and call the play() and pause() functions to control the playback and pause of the music. Of course, this is just the simplest example of a music player, and more functions and styles can be added to expand it.

The complete code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音乐播放器</title>
        <style>
.container {
      
      
    text-align: center;
    margin-top: 10%;
}
h1 {
      
      
    font-size: 3em;
    margin-bottom: 30px;
}
button {
      
      
    margin-top: 20px;
    font-size: 1.5em;
}
    </style>
</head>
<body>
    <div class="container">
        <h1>音乐播放器</h1>
        <audio id="myAudio" controls>
            <source src="music.mp3" type="audio/mpeg">
        </audio>
        <button id="playButton">播放</button>
        <button id="pauseButton">暂停</button>
    </div>
    <script>
var myAudio = document.getElementById("myAudio");
var playButton = document.getElementById("playButton");
var pauseButton = document.getElementById("pauseButton");
playButton.addEventListener("click", function() {
      
      
    myAudio.play();
});
pauseButton.addEventListener("click", function() {
      
      
    myAudio.pause();
});
    </script>
</body>
</html>

The interface effect is as follows:
simple music playback

Guess you like

Origin blog.csdn.net/dica54dica/article/details/130191720