As people become more and more dependent on network applications, the functions of various websites are also constantly upgraded. These functions usually require repeated operations by users, but without sound prompts, users may easily miss them, thus affecting the experience. This article will introduce how to use PHP to add notification sounds to your website.
1. HTML5 audio tag
To play sound on a website, the most direct way is to use the HTML5 audio tag. For example, the following code will play my prompt sound "Ding" in the web page:
<audio src="ding.mp3" autoplay></audio>
The src
attribute here specifies the path of the audio file, and "autoplay" means that it will play as soon as the page is entered. will play automatically.
2. Use JavaScript to play sounds
The audio tag of HTML5 has a significant disadvantage, that is, it can only play fixed sound files and cannot be dynamically specified in the code. To solve this problem, we can use JavaScript to play sounds.
First, we need to define a function playSound()
to play sound. There are many ways to implement this function. Here we use the Audio
object:
function playSound(soundFile) { var audio = new Audio(soundFile); audio.play(); }
Then, when triggering sound in the web page, you can call this function and pass in the path of the sound file. For example, the following button will play "ding.mp3" when clicked:
<button onclick="playSound('ding.mp3')">Ding!</button>
3. Use JavaScript to play sounds in PHP
Now we can use JavaScript to play sounds in web pages , but what if you want to trigger sound in PHP? It's actually very simple, you just need to embed JavaScript code in PHP code.
For example, the following PHP code will output a submit button with a sound prompt:
<input type="submit" value="提交" onclick="playSound('ding.mp3')">
The onclick
attribute here specifies the JavaScript to be executed when the button is clicked Code, that is, call the playSound()
function and pass in the path of the sound file.
4. Dynamically generate JavaScript code in PHP
Sometimes we need to dynamically generate JavaScript code based on certain conditions in PHP. At this time, we can use PHP’s echo
statement to generate JavaScript code.
For example, the following PHP code will dynamically generate a button with a sound prompt based on the value of the $count
variable:
<?php $count = 3; echo '<input type="button" value="点击" onclick="playSound(\'ding.mp3\')">'; for ($i = 0; $i < $count; $i++) { echo '<input type="button" value="按钮 '.$i.'" onclick="playSound(\'ding.mp3\')">'; } ?>
Hereecho## The # statement is used to output HTML markup and JavaScript code. Note that since single quotes cannot be contained within single quotes, they must be escaped with backslashes.
The above is the detailed content of How to add prompt sound to website in php. For more information, please follow other related articles on the PHP Chinese website!