php method to implement sound playback: 1. Create a PHP sample file; 2. Read the database through PHP; 3. Create an HTML sample file and use H5 audio() to play the prompt sound. .
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How does php play sound?
PHP uses H5 audio to achieve sound prompts similar to Meituan orders and music playback effects on web pages
We often do in-site messages and message reminder functions, so how to add on this basis What about the beep? Today I will share with you the entire function implementation process.
First we need to lay out the good news prompt style. Here you can lay it out according to your own needs.
After making the message prompt style, we need to start making timers and asynchronous query data.
<script> $(function () { var set = setInterval(function(){ $.post("{:url('prompt')}", '', function(data){ if (data.status){ $('#num').html(data.num); //将消息数量添加上去 var audio = new Audio("./song.ogg"); //获取本地音频文件,ogg,mp3都可以 audio.play(); //执行播放操作 } }, 'json'); }, 1000); //点击查看小心,并且将消息数量清空 $('#a_link').click(function () { $('#num').html(''); }) }) </script>
Here we use H5’s audio() to play the prompt sound. The code I wrote here is very rough, you can optimize it according to your own needs.
Below we use PHP language to read when there are new messages in the database. If there are new messages, start pushing, if not, ignore them. What I am here is based on TP5.1
public function prompt() { //这里插叙是否有新订单,如果有就提示,没有则忽略 $num = Db::name('hexiao')->where('add_time', '>' , date('Y-m-d H:i:s', time()-10))->count(); if ($num > 0){ return json(['status' => 1, 'num' => $num]); } else { return json(['status' => 0, 'num' => $num]); } }
The following introduces the audio tag of H5, which currently supports MP3, Ogg, and Wav
<audio> <source> <source> 您的浏览器不支持 audio 元素。 </source></source></audio>
Execution effect
Execution effect.png
You can also control playback, pause and replay
<audio></audio> <span>播放/暂停</span> <span>重播</span>
You can also control audio playback and pause through js
<script> function repeat(){ var audio = document.getElementById('music'); audio.currentTime = 0;//重新播放 } function control(){ var audio = document.getElementById('music'); if(audio!==null){ if(audio.paused){ audio.play();// 播放 }else{ audio.pause();// 暂停 } } } </script>
The above is Have you learned the complete process?
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to play sound in php. For more information, please follow other related articles on the PHP Chinese website!