program story

웹 사이트에서 알림 음을 재생하는 방법은 무엇입니까?

inputbox 2020. 9. 1. 07:29
반응형

웹 사이트에서 알림 음을 재생하는 방법은 무엇입니까?


특정 이벤트가 발생하면 웹 사이트에서 사용자에게 짧은 알림 음을 재생하고 싶습니다.

웹 사이트가 열릴 때 소리가 (즉시) 자동 시작 되지 않아야합니다 . 대신 JavaScript를 통해 요청시 재생되어야합니다 (특정 이벤트가 발생할 때).

이전 브라우저 (IE6 등)에서도 작동하는 것이 중요합니다.

따라서 기본적으로 두 가지 질문이 있습니다.

  1. 어떤 코덱을 사용해야합니까?
  2. 오디오 파일을 포함하는 가장 좋은 방법은 무엇입니까? ( <embed>vs. <object>vs. 플래시 vs. <audio>)

이 솔루션은 거의 모든 브라우저에서 작동합니다 (플래시가 설치되지 않았더라도).

<!doctype html>
<html>
  <head>
    <title>Audio test</title>
    <script>
      /**
        * Plays a sound using the HTML5 audio tag. Provide mp3 and ogg files for best browser support.
        * @param {string} filename The name of the file. Omit the ending!
        */
      function playSound(filename){
        var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
        var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
        var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
        document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
      }
    </script>
  </head>

  <body>
    <!-- Will try to play bing.mp3 or bing.ogg (depends on browser compatibility) -->
    <button onclick="playSound('bing');">Play</button>  
    <div id="sound"></div>
  </body>
</html>

브라우저 지원

사용 된 코드

  • Chrome, Safari 및 Internet Explorer 용 MP3.
  • Firefox 및 Opera 용 OGG.

2016 년부터는 다음으로 충분합니다 (삽입 할 필요도 없음).

let audio = new Audio('/path/to/audio/file.mp3');
audio.play();

여기에서 더 많은 것을 보십시오 .


웹 사이트에서 알림 소리를 재생하는 플러그인 하나 더 : Ion.Sound

장점 :

  • HTML5 오디오로 대체되는 Web Audio API 기반 사운드 재생을위한 JavaScript 플러그인.
  • 플러그인은 가장 널리 사용되는 데스크톱 및 모바일 브라우저에서 작동하며 일반적인 웹 사이트에서 브라우저 게임에 이르기까지 모든 곳에서 사용할 수 있습니다.
  • 오디오 스프라이트 지원이 포함되어 있습니다.
  • 종속성이 없습니다 (jQuery가 필요하지 않음).
  • 25 가지 무료 사운드가 포함되어 있습니다.

플러그인 설정 :

// set up config
ion.sound({
    sounds: [
        {
            name: "my_cool_sound"
        },
        {
            name: "notify_sound",
            volume: 0.2
        },
        {
            name: "alert_sound",
            volume: 0.3,
            preload: false
        }
    ],
    volume: 0.5,
    path: "sounds/",
    preload: true
});

// And play sound!
ion.sound.play("my_cool_sound");

야후의 미디어 플레이어는 어때 야후의 라이브러리를 삽입하세요

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

그리고 그것을 다음과 같이 사용하십시오.

<a id="beep" href="song.mp3">Play Song</a>

자동 시작하려면

$(function() { $("#beep").click(); });

크로스 브라우저 호환 알림 재생

게시물의 @Tim Tisdall 조언 한대로 Howler.js 플러그인을 확인하십시오 .

Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.

  var sound =new Howl({
                     src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
                           '../sounds/rings.aiff'],
                     autoplay: true,
                     loop: true
                    });

               sound.play();

Hope helps someone.


Use the audio.js which is a polyfill for the <audio> tag with fallback to flash.

In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills for polyfills to the HTML 5 APIs.. (it includes more <audio> polyfills)


var audio = new Audio('audio_file.mp3');

function post()
{
  var tval=document.getElementById("mess").value;   
  var inhtml=document.getElementById("chat_div");
  inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
  inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
  audio.play();
}

this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php


We can just use Audio and an object together like:

var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();

and even adding addEventListener for play and ended


I wrote a clean functional method of playing sounds:

sounds = {
    test : new Audio('/assets/sounds/test.mp3')
};

sound_volume = 0.1;

function playSound(sound) {
    sounds[sound].volume = sound_volume;
    sounds[sound].play();
}
function stopSound(sound) {
    sounds[sound].pause();
}
function setVolume(sound, volume) {
    sounds[sound].volume = volume;
    sound_volume = volume;
}

참고URL : https://stackoverflow.com/questions/10105063/how-to-play-a-notification-sound-on-websites

반응형