【问题标题】:How to add error sound in PHP using javascript or jquery如何使用 javascript 或 jquery 在 PHP 中添加错误声音
【发布时间】:2021-04-08 07:06:31
【问题描述】:

需要知道当用户输入错误密码时如何在 PHP 中添加一个小的错误声音。下面是正在使用的代码。我知道我必须使用 js 或 jquery 来播放声音,并希望有人可以帮助我。在此先感谢。

<?php
    include "header.php";

    if (isset($_GET['loginFailed'])) {
        $message = "Invalid Credentials ! Please try again.";
        echo "<script type='text/javascript'>alert('$message');</script>";
    }
?>

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="admin_login_style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>


<body>
    <form action="./admin_login_action.php" method="post">
        <div class="flex-container-1">
            <div class="flex-item">
                <h2>Administrator Login</h2>
            </div>

            <label><b>Username</b></label>
            <div class="flex-item">
                <input type="text" name="admin_uname" required>
            </div>

            <label><b>Password</b></label>
            <div class="flex-item">
                <input type="password" name="admin_psw" required>
            </div>
        </div>

        <div class="flex-container-2">
            <div class="flex-item">
                <button type="submit">Login</button>
            </div>

            <div class="flex-item">
                <button type="button" class="cancelbtn">Cancel</button>
            </div>
        </div>
    </form>

</body>
</html>

【问题讨论】:

  • 您的错误声音 mp3 文件在哪里?只播放错误 mp3 文件而不是警报。
  • 嗨对不起我是新手,你能解释一下如何导入文件和播放

标签: javascript php jquery css


【解决方案1】:

出于安全考虑,Chrome 或某些现代浏览器不会在没有用户交互的情况下自动播放声音。

如果我们尝试在页面加载时播放声音,控制台中会出现以下警告消息。

Uncaught (in promise) DOMException: play() failed 因为用户 没有先与文档交互。 https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

您可以使用以下 2 种我认为是最好的方法通过一些交互来播放声音。

使用默认 HTML+JS 方法:

<audio id="my_audio" src="http://www.noiseaddicts.com/samples_1w72b820/3724.mp3" loop="loop"></audio>
document.getElementById("my_audio").play(); // Using JS
// $("#my_audio").get(0).play(); // Using jQuery

使用 jQuery playSound 库:

<script src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script src='https://cdn.rawgit.com/admsev/jquery-play-sound/master/jquery.playSound.js'></script>
<script>
$.playSound("http://www.noiseaddicts.com/samples_1w72b820/3724.mp3");
</script>

【讨论】:

    【解决方案2】:

    您可以使用 PHP 在出错时回显 html 音频标签...

    if (isset($_GET['loginFailed'])) {
            $message = "Invalid Credentials ! Please try again.";
            echo "<script type='text/javascript'>alert('$message');</script>";
            echo '<audio autoplay><source src="error.mp3"></audio>';  
        }
    

    唯一的缺点是现在的浏览器会要求用户允许自动播放声音。就像另一个答案中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2013-07-08
      • 1970-01-01
      相关资源
      最近更新 更多