简体   繁体   English

如何在不复制 javascript 功能的情况下创建多个音频播放器(每个播放器包含不同的歌曲)?

[英]How can i create multiple audio players(each containing different song) without copying javascript functionality?

I dont know if my title is clear enough so ill try my best to sumerize.我不知道我的标题是否足够清楚,所以我会尽力总结。 I created audio player containing one song using audio tag.我使用音频标签创建了包含一首歌曲的音频播放器。 I made all functionality in javascript for player(progress bar, volume bar, play pause stop, time etc..) and now i want to repeat same plyer in column.我在 javascript 中为播放器制作了所有功能(进度条、音量条、播放暂停停止、时间等),现在我想在列中重复相同的层。 I copied html and everything is ok but second player with different song is not triggering javascript even though all classes are the same.我复制了 html 并且一切正常,但是即使所有类都相同,具有不同歌曲的第二个播放器也不会触发 javascript。

My goal is to create something similar to soundcloud website where each audio has its own audio player but i dont want to copy javascript code for every audio.我的目标是创建类似于 soundcloud 网站的内容,其中每个音频都有自己的音频播放器,但我不想为每个音频复制 javascript 代码。 Is there a way to do this using same variables?有没有办法使用相同的变量来做到这一点?

Code is huge btw :).顺便说一句,代码很大:)。

HTML:

<!-- AUDIO PLAYER -->
    <div class="mainPlayerDiv">
        <h1>Amelie Lens - Hypnotized</h1>
        <div class="mainPlayer">
            <div class="audioPlayerDiv">
                <div class="playPauseBtn">
                    <div class="btnLine"></div>
                    <div class="btnLine"></div>
                    <div class="btnLine"></div>
                </div>
                <div class="stopBtnDiv">
                    <div class="stopBtn"></div>
                </div>
                <i class="fas fa-volume-down volumeDownIcon"></i>  
                <div class="mainVolumeDiv">
                    <div class="volumeBar" id="volumeBar">
                        <div id="volume"></div>
                    </div>
                    <span id="volPercentage"></span>                    
                </div> 

                <div class="trackTime">
                    <span id="currTime"></span> /
                    <span id="duration"></span>
                </div> 
            </div>
            <a class="dlLink" href="/Track/Amelie Lens - Hypnotized.mp3" download="Amelie Lens - Hypnotized">
                <button class="freeDownload">
                    <h5>mp3</h5>
                    <h3>Free Download</h3>
                </button>
            </a>
            <button class="buyTrack">
                <h3>Buy This Beat</h3>
            </button>
        </div>
        <!--<canvas id="progress" width="500" height="10"></canvas>-->
        <audio id="audio" class="track" src="/Track/Amelie Lens - Hypnotized.mp3" download></audio>
        <div class="progressBarCont" id="progressBarCont">
            <div class="progress" id="progress"></div> 
        </div>
    </div>


Javascript:
// AUDIO PLAYER
var audioEl = document.querySelector('.track');
audioEl.addEventListener('loadedmetadata', function(){
    var duration = audioEl.duration;
    var currentTime = audioEl.currentTime;
    document.getElementById("duration").innerHTML = convertElapsedTime(duration);
    document.getElementById("currTime").innerHTML = convertElapsedTime(currentTime);
    audioEl.volume = 0.31;  
    document.getElementById("volPercentage").innerHTML = 30 + " %";
});
// TIME UP
audioEl.addEventListener("timeupdate", function(){
    var timeline = document.getElementById("currTime");
    var s = parseInt(audioEl.currentTime % 60);
    var m = parseInt((audioEl.currentTime / 60) % 60);
    if (s < 10) {
        timeline.innerHTML = m + ':0' +s;

    } else {
        timeline.innerHTML = m + ':' +s;
    }
    if (audioEl.ended) {
        playPauseBtn.classList.remove('transform');
        stopBtnDiv.classList.add('transform');
        audioEl.currentTime = 0;
        percent = 0;
        progress.style.width = '0';
        stopped = true;
        clearInterval(interval);
        clearInterval(interval2);
        audioPlayerDiv.classList.remove('playAnimation'); 
        audioPlayerDiv.classList.remove('playAnimation2'); 
    }
 }, false);
// OVERALL DURATION
function convertElapsedTime(inputSeconds) {
    var seconds = Math.floor(inputSeconds % 60);
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    var minutes = Math.floor(inputSeconds / 60);

    return minutes + ":" + seconds;
}
// PROGRESS BAR
var timer;
var percent = 0;
var audioEl = document.getElementById("audio");
audioEl.addEventListener("playing", function(_event) {
  var duration = _event.target.duration;
  advance(duration, audioEl);
});
audioEl.addEventListener("pause", function(_event) {
  var progress = document.getElementById("progress");
  clearTimeout(timer);
});
var advance = function(duration, element) {
  var progress = document.getElementById("progress");
  increment = 10/duration
  percent = Math.min(increment * element.currentTime * 10, 100);
  progress.style.width = percent+'%'
  startTimer(duration, element);
}
var startTimer = function(duration, element){ 
  if(percent < 100) {
    timer = setTimeout(function (){advance(duration, element)}, 100);
  }
}
// PROGRESS BAR SEEK
var progressBarCont = document.getElementById('progressBarCont');
var progress = document.getElementById("progress");

progressBarCont.addEventListener("mousedown", function(event){
    var viewportset = progressBarCont.getBoundingClientRect();    
    var clickedPos = event.clientX - viewportset.left;
    audioEl.currentTime = (clickedPos / event.target.offsetWidth) * audioEl.duration;
}, false);
// PROGRESS BAR END
/* 
            VOLUME SLIDER
*/
var volumeSlider = document.getElementById("volume");
var volumeBar = document.getElementById("volumeBar");
volumeBar.addEventListener('click', function(e){
    var viewportOffset = volumeBar.getBoundingClientRect();
    var cursorPosition;
    cursorPosition = Math.floor(e.clientX - viewportOffset.left);

    if(cursorPosition <= 9) {
        audioEl.volume = '0.0' + cursorPosition;      
        document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
        volumeSlider.style.width = cursorPosition + "px";
    } else if (cursorPosition === 100) {
        audioEl.volume = 1;     
        document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
        volumeSlider.style.width = cursorPosition + "px";
    } else {
        audioEl.volume = '0.' + cursorPosition;      
        document.getElementById("volPercentage").innerHTML = cursorPosition + " %";
        volumeSlider.style.width = cursorPosition + "px";
    }
    if(cursorPosition >= 50) {
        volumeIconBtn.classList.remove('.fas'); 
        volumeIconBtn.classList.remove('fa-volume-mute'); 
        volumeIconBtn.classList.add('.fas'); 
        volumeIconBtn.classList.add('fa-volume-up'); 
        audioDownUp = 2;
    } else {
        volumeIconBtn.classList.remove('.fas'); 
        volumeIconBtn.classList.remove('fa-volume-up'); 
    }
    if (cursorPosition <= 49) {
        volumeIconBtn.classList.remove('.fas'); 
        volumeIconBtn.classList.remove('fa-volume-mute'); 
        volumeIconBtn.classList.add('.fas'); 
        volumeIconBtn.classList.add('fa-volume-down'); 
        audioDownUp = 1;
    } else {
        volumeIconBtn.classList.remove('.fas'); 
        volumeIconBtn.classList.remove('fa-volume-down'); 
    }
    volPercentage.classList.add('showVolPercent');
    setTimeout(function(){
        volPercentage.classList.remove('showVolPercent');
    }, 5000);
}); 
///////////////////// VOLUME SLIDER END
const playPauseBtn = document.querySelector('.playPauseBtn');
const stopBtnDiv = document.querySelector('.stopBtnDiv');
const stopBtn = document.querySelector('.stopBtn');
playPauseBtn.addEventListener('click', playPauseFunction);
stopBtnDiv.addEventListener('click', stopFunction);
let stopped = true;
var interval;
var interval2;

function playPauseFunction() {
    if(audioEl.paused) {
        playPauseBtn.classList.add('transform');
        playPauseBtn.classList.add('transform2');
        setTimeout(function(){ 
            playPauseBtn.classList.remove('transform2'); 
        }, 200);
        audioEl.play();
        audioEl2.play();
        stopped = false;

        let animation = 1;

        interval = setInterval(function() {
            if(animation === 1) {
                audioPlayerDiv.classList.add('playAnimation'); 
                animation = 0;                 
            } else {
                audioPlayerDiv.classList.remove('playAnimation'); 
                animation = 1;
            }
        },16000);
        let animation2 = 1;
        interval2 = setInterval(function() {
            if(animation2 === 1) {
                audioPlayerDiv.classList.add('playAnimation2'); 
                animation2 = 0;                 
            } else {
                audioPlayerDiv.classList.remove('playAnimation2'); 
                animation2 = 1;
            }
        },32000);
    } else {
        playPauseBtn.classList.remove('transform');
        playPauseBtn.classList.add('transform2');
        setTimeout(function(){ 
            playPauseBtn.classList.remove('transform2'); 
        }, 200);
        audioEl.pause();
        stopped = false;

        clearInterval(interval);
        clearInterval(interval2);
        audioPlayerDiv.classList.remove('playAnimation'); 
        audioPlayerDiv.classList.remove('playAnimation2'); 

    }
}
function stopFunction() {
    if(!audioEl.paused) { // IF PLAYING
        playPauseBtn.classList.remove('transform');
        stopBtnDiv.classList.add('transform2');
        stopBtnDiv.classList.add('transform');
        setTimeout(function(){ 
            stopBtnDiv.classList.remove('transform');
            stopBtnDiv.classList.remove('transform2'); 
        }, 200);
        clearInterval(interval);
        clearInterval(interval2);
        audioPlayerDiv.classList.remove('playAnimation'); 
        audioPlayerDiv.classList.remove('playAnimation2'); 
        audioEl.currentTime = 0;
        percent = 0;
        progress.style.width = '0';
        stopped = true;
        audioEl.pause();
    } else if (audioEl.paused && !stopped) {
        stopBtnDiv.classList.add('transform');
        stopBtnDiv.classList.add('transform2');
        setTimeout(function(){ 
            stopBtnDiv.classList.remove('transform');
            stopBtnDiv.classList.remove('transform2'); 
        }, 200);
        clearInterval(interval);
        clearInterval(interval2);
        audioPlayerDiv.classList.remove('playAnimation'); 
        audioPlayerDiv.classList.remove('playAnimation2'); 
        audioEl.currentTime = 0;
        percent = 0;
        progress.style.width = '0';
        stopped = true;
    } else if (stopped){
        audioEl.currentTime = 0;
        percent = 0;
        progress.style.width = '0';
        stopped = true;
    }
}


here's ss of players这是玩家的 ss

Many thanks in advance.提前谢谢了。

You could use the Audio() constructor.您可以使用Audio()构造函数。

const player = (audiofile) => {
  const newPlayer = new Audio(audiofile)
  return newPlayer
}

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

Then create a new player by calling player('audio.wav')然后通过调用player('audio.wav')创建一个新的播放player('audio.wav')

ADDED:添加:

Now that I can see your code, the other way to create many players dynamically is:现在我可以看到您的代码,另一种动态创建多个玩家的方法是:

  1. Create an array for your audio files:为您的音频文件创建一个数组:
const tracks = ['track1.wav', 'track2.wav']
  1. Add a container for your players in your HTML在 HTML 中为玩家添加容器
<div id="players"></div>
  1. Add a function that creates a player and appends it to the container dynamically添加创建播放器并将其动态附加到容器的函数
const players = document.getElementById('players')

const player = (audiofile) => {
  const newPlayer = document.createElement('audio')
  audio.src = audiofile
  // anything else you want to add
  }
  players.appendChild(newPlayer)
}

The audio() constructor and createElement(audio) both create new audio element, but audio() does not interact with the DOM. audio()构造函数和createElement(audio)都创建新的音频元素,但audio()不与 DOM 交互。

  1. Lastly, you would have to create a function that renders as many players as there are tracks.最后,您必须创建一个函数来渲染与轨道一样多的播放器。

Once you have rendered the players successfully, you should add an event listener for you controls so that the correct audio is played when user clicks on play etc.成功渲染播放器后,您应该为控件添加一个事件侦听器,以便在用户单击播放等时播放正确的音频。

https://developer.mozilla.org/en-US/docs/Web/API/Event/target https://developer.mozilla.org/en-US/docs/Web/API/Event/target

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按阵列长度加载多个音频播放器,并在每个播放器上播放不同的声音? - How to load multiple audio players by array's length and play different sound on each? 循环播放多个单首歌曲音频播放器以连续播放 - Looping multiple single song audio players for continuous play 多个音频播放器彼此暂停 - Multiple audio players pause each other 当其中一个停止 javascript 时,如何播放其他音频/歌曲? - How can i make other audio/song be played when one of them stops javascript? 如何在 JavaScript 中播放时加载下一首音频歌曲? - How can i load next audio song while one is playing in JavaScript? 如何在不使用 eval 的情况下使用 JavaScript 的功能来创建计算器? - How can I use JavaScript's functionality to create a calculator without using eval? 如何创建允许用户在 JavaScript 中多次过滤的功能? - How can I create functionality that allows the user to filter multiple times in JavaScript? 如何更改此功能,以便每次单击一次只能播放一首随机歌曲? (JavaScript) - How do I alter this function so that only one, random song can be played at a time with each click? (JavaScript) 如何在一个页面上有两个这样的音频播放器,而又不单击另一个播放器或显示隐藏播放列表 - How can i have two of these audio players on one page, without clicking on one and the other one play or show hide playlist 如何在不阻止功能的情况下编辑此Javascript? - How can I edit this Javascript without blocking functionality?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM