Home >Backend Development >PHP Tutorial >How to write a simple online audio player via PHP
How to write a simple online audio player through PHP
In today's Internet era, the dissemination and sharing of audio resources is becoming more and more convenient. Therefore, it is necessary to develop an An online audio player becomes a very practical and fun project. This article will introduce how to write a simple online audio player through PHP and provide specific code examples.
To implement an online audio player, we need the following elements:
First, we need an interface layout to display the audio player. Create an HTML file, for example player.html
, and add the following code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Online Audio Player</title> </head> <body> <h1>Online Audio Player</h1> <audio id="audioPlayer" controls> <source src="audio.mp3" type="audio/mpeg"> </audio> </body> </html>
In the above code, we have used the <audio></audio>
tag to create An audio player, and specify the src
attribute as audio.mp3
. This path can be modified according to the actual situation. Open player.html
in your browser and you will see a basic audio player interface.
Next, we need to implement the audio resource management function. Create a PHP file, such as upload.php
, and add the following code:
<?php if($_FILES["audio"]["error"] == UPLOAD_ERR_OK) { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["audio"]["name"]); if(move_uploaded_file($_FILES["audio"]["tmp_name"], $target_file)) { echo "上传成功!"; } else { echo "上传失败!"; } } ?>
In the above code, we receive the audio uploaded by the user through the $_FILES
variable document. First check whether the file upload is successful. If successful, move the file to the specified directory (uploads/
in the example), and finally output the corresponding information.
Then, we need to implement the function of the playback controller. Modify the code of the player.html
file, add a <script></script>
tag, and add the following code inside it:
<script> var audioPlayer = document.getElementById("audioPlayer"); audioPlayer.onplay = function() { console.log("音频播放中..."); } audioPlayer.onpause = function() { console.log("音频暂停。"); } audioPlayer.onvolumechange = function() { console.log("音量变化:" + audioPlayer.volume); } </script>
In the above code, we pass # The ##getElementById method obtains the object of the audio player and adds some event listeners to output corresponding information when the audio is played, paused, and the volume changes.
player.html file, add a