development

버튼 클릭시 jQuery를 사용하여 오디오 파일 재생

big-blog 2020. 9. 15. 18:57
반응형

버튼 클릭시 jQuery를 사용하여 오디오 파일 재생


버튼을 클릭 할 때 오디오 파일을 재생하려고하는데 작동하지 않습니다. 내 HTML 코드는 다음과 같습니다.

<html>    
    <body>
        <div id="container">
            <button id="play">
                Play Music
            </button>
        </div>
    </body>
</html>

내 JavaScript는 다음과 같습니다.

$('document').ready(function () {
    $('#play').click(function () {
        var audio = {};
        audio["walk"] = new Audio();
        audio["walk"].src = "http://www.rangde.org/static/bell-ring-01.mp3"
        audio["walk"].addEventListener('load', function () {
            audio["walk"].play();
        });
    });
});   

나는 그것을 위해 Fiddle 도 만들었 습니다.


어떤 접근법?

당신은 오디오를 재생할 수 있습니다 <audio>태그 또는 <object><embed>. Lazy loading (필요할 때로드) 크기가 작은 경우 사운드가 가장 좋은 방법입니다. 오디오 요소를 동적으로 만들 수 있으며로드되면로 시작하고로 .play()일시 중지 할 수 있습니다 .pause().

우리가 사용한 것들

canplay이벤트를 사용 하여 파일을 재생할 준비가되었는지 확인합니다.

.stop()오디오 요소에 대한 기능 이 없습니다 . 일시 중지 만 할 수 있습니다. 그리고 오디오 파일의 처음부터 시작하려면 .currentTime. 이 행을 예제에서 사용합니다 audioElement.currentTime = 0;. .stop()기능 을 얻기 위해 먼저 파일을 일시 중지 한 다음 시간을 재설정합니다.

오디오 파일의 길이와 현재 재생 시간을 알고 싶을 수 있습니다. 우리 .currentTime가 사용하는 길이를 배우기 위해 위에서 이미 배웠습니다 .duration.

예제 가이드

  1. 문서가 준비되면 오디오 요소를 동적으로 만들었습니다.
  2. 우리는 재생할 오디오로 소스를 설정합니다.
  3. 파일을 다시 시작하기 위해 '종료'이벤트를 사용했습니다.

currentTime이 지속 시간과 같으면 오디오 파일 재생이 중지됩니다. 를 사용할 때마다 play()처음부터 시작됩니다.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

$(document).ready(function() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');
    
    audioElement.addEventListener('ended', function() {
        this.play();
    }, false);
    
    audioElement.addEventListener("canplay",function(){
        $("#length").text("Duration:" + audioElement.duration + " seconds");
        $("#source").text("Source:" + audioElement.src);
        $("#status").text("Status: Ready to play").css("color","green");
    });
    
    audioElement.addEventListener("timeupdate",function(){
        $("#currentTime").text("Current second:" + audioElement.currentTime);
    });
    
    $('#play').click(function() {
        audioElement.play();
        $("#status").text("Status: Playing");
    });
    
    $('#pause').click(function() {
        audioElement.pause();
        $("#status").text("Status: Paused");
    });
    
    $('#restart').click(function() {
        audioElement.currentTime = 0;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <h2>Sound Information</h2>
    <div id="length">Duration:</div>
    <div id="source">Source:</div>
    <div id="status" style="color:red;">Status: Loading</div>
    <hr>
    <h2>Control Buttons</h2>
    <button id="play">Play</button>
    <button id="pause">Pause</button>
    <button id="restart">Restart</button>
    <hr>
    <h2>Playing Information</h2>
    <div id="currentTime">0</div>
</body>


The actual answer, in jQuery, is

$("#myAudioElement")[0].play();

It doesn't work with $("#myAudioElement").play() like you would expect. The official reason is that incorporating it into jQuery would add a play() method to every single element, which would cause unnecessary overhead. So instead you have to refer to it by its position in the array of DOM elements that you're retrieving with $("#myAudioElement"), aka 0.

This quote is from a bug that was submitted about it, which was closed as "feature/wontfix":

To do that we'd need to add a jQuery method name for each DOM element method name. And of course that method would do nothing for non-media elements so it doesn't seem like it would be worth the extra bytes it would take.


For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:

audio.mp3

for

http://www.uscis.gov/files/nativedocuments/Track%2093.mp3

linking in a freely available mp3 off the web. Thank you for sharing the easy solution!


I here have a nice and versatile solution with a fallback:

<script type="text/javascript">
    var audiotypes={
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }

    function ss_soundbits(sound){
        var audio_element = document.createElement('audio')
        if (audio_element.canPlayType){
            for (var i=0; i<arguments.length; i++){
                var source_element = document.createElement('source')
                source_element.setAttribute('src', arguments[i])
                if (arguments[i].match(/\.(\w+)$/i))
                    source_element.setAttribute('type', audiotypes[RegExp.$1])
                audio_element.appendChild(source_element)
            }
            audio_element.load()
            audio_element.playclip=function(){
                audio_element.pause()
                audio_element.currentTime=0
                audio_element.play()
            }
            return audio_element
        }
    }
</script>

After that you can initialize as many audio as you like:

<script type="text/javascript" >
    var clicksound  = ss_soundbits('your/path/to/click.ogg', "your/path/to/click.mp3");
    var plopsound  = ss_soundbits('your/path/to/plopp.ogg', "your/path/to/plopp.mp3");
</script>

Now you can reach the initialized audio element whereever you like with simple event calls like

onclick="clicksound.playclip()"

onmouseover="plopsound.playclip()"

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

참고URL : https://stackoverflow.com/questions/8489710/play-an-audio-file-using-jquery-when-a-button-is-clicked

반응형