如何按阵列长度加载多个音频播放器并在每个播放器上播放不同的声音?

时间:2016-02-20 22:33:13

标签: javascript html css audio

我试图在一个HTML页面上出现的不同音频播放器上加载不同的声音(.mp3音频)。也就是说,阵列的长度决定了屏幕上出现的玩家数量。所以,在这个例子中,我在数组中有3个元素。因此,3个音频播放器播放3种不同的东西。

我设法在页面上放置了3个玩家,就像我对他们的同等文本(动物的声音)所做的一样,但我面临以下问题:< / p>

  1. 每位玩家正在播放相同的声音,而不是为不同的播放器播放每个播放器。 我使用了#34; for循环&#34;通过数组递增,但我找不到让它记住&#34;记住&#34;旧音频所以它总是播放所有播放器的最后声音。在这种情况下,它只播放&#34; Cat&#34;。

  2. 即使我点击空行,在第1和第2个玩家之间,没有音频播放器 - 声音仍然在播放,我可以&#39;弄清楚为什么......

  3. 我非常感谢任何帮助!!!

    &#13;
    &#13;
    //use JQuery to grab the audioID and play the audio 
    jQuery(document).ready(function() {
    	var speakWord = document.getElementsByClassName('speakout');
    			var nowPlaying = speakWord[0];
    			nowPlaying.load();
    			$("#divAudio").on("click", function() {
    			nowPlaying.play();
    			});
    	});	
    
    var textBox = document.getElementById('inBox');   			//Responsible for printing words
    var player = document.getElementById('myPlayer');			//PLAYING the sound (<audio>)
    var outArr = ['Dog', 'Cow','Cat'];
    var pathArr = ['http://cd.textfiles.com/mmplus/MEDIA/WAV/EFFECTS/BARK.WAV', 'http://www.internetstart.se/download/ljud/moo.wav', 'http://area512.htmlplanet.com/wavs/blackcat.wav'];
    var audioLogo = document.getElementById('divAudio');		//for the APPEREANCE of the audio player (LOGO)
    var img_audio = document.createElement("IMG");				// properties of the IMAGE 
    br = document.createElement("br");          			//creating a break in the document 
    var new_audio = document.createElement("audio");
    
    var points = 50;
    
    if(outArr.constructor === Array) {
    	//audioLogo.style.display = "initial";
    	for(i=0; i < outArr.length; ++i) {
    		
    		//regarding the TEXT elements:
    		textBox.innerHTML += outArr[i]+'<br>';  
    		textBox.style.fontSize = "30px";
    		textBox.style.position = "absolute";
    		textBox.style.top = String(points)+'pt';
    		textBox.style.marginRight= "5pt";
    		textBox.style.lineHeight = "71pt";
    		textBox.style.right = '5pt';	
    	}
    }
    else {
    	textBox.innerHTML += outArr;
    	textBox.style.fontSize = "30px";
    	textBox.style.position = "absolute";
    	textBox.style.top = "76pt";
    }
    var points = 70;
    for(i=0; i < pathArr.length; ++i) {
    			var new_audio = document.createElement("audio");
    			var multiAud = audioLogo.querySelectorAll('.multiple_audio');
    			
    			imgArr =  Array(pathArr.length).fill('http://www.coli.uni-saarland.de/~andreeva/powin/images/sound.png');
    			if(i<1){
    			img_audio.style.height = "9%";  //the size of the audio logo
    			img_audio.style.width = "9%";
    			img_audio.setAttribute("src", imgArr[i]); //creating an attribute (image) to be added to doc
    			audioLogo.style.position = "absolute";   
    			audioLogo.style.top = '58pt';		
    			audioLogo.style.lineHeight = "73pt";
    			player.src = pathArr[i]; 
    			audioLogo.appendChild(img_audio); 
    			audioLogo.innerHTML +=  '<br>';
    			}
    			else {
    			var audio = new Audio(pathArr[i]);
    			audio.className = 'multiple_audio';
    			img_audio.style.height = "9%";
    			img_audio.style.width = "9%";
    			img_audio.setAttribute("src", imgArr[i]); //creating an attribute (image) to be added to doc
    			audioLogo.style.position = "absolute";
    			audioLogo.style.top = '58pt';
    			audioLogo.style.lineHeight = "73pt";
    			audioLogo.appendChild(img_audio);
    			player.src = pathArr[i]; 
    			audioLogo.innerHTML +=  '<br>';
    			//player.parentNode.insertBefore(audio , player.nextNode); 
    			}
    			
    		}
    &#13;
    #layout {
    position: relative;
    overflow: auto;
    left: 225px;
    width: 	800px;
    height: 370px;
    background-color: white;  
    padding-left: 1px;
    max-width:100%;
    }
    
    #myText {
    pointer-events: none;
    width: 	800px;
    height: 370px;
    resize: none;
    font-size: 45px;
    font-family: Arial, Helvetica, Verdana;
    background: url(https://qph.is.quoracdn.net/main-qimg-47327da6ae3e0b3727a9b9a7ea7f1adb?convert_to_webp=true);
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <html lang="en">
        <head>
    	<meta charset="utf-8"/>
        <script type="text/javascript" src="jquery-1.11.3.js"></script>
        </head>
        <body>
    	<br>
    		<div id="layout" readonly="readonly">
    		<div contenteditable maxlength="200" readonly="readonly" id="myText" dir="auto" name="outtest" class = "fetchBox"></div> 
    		<div id="inBox" class="fetch" dir="auto"></div>
    		
    		 <audio class="speakout" id="myPlayer"> 
    
    			Your Browser does not support the HTML audio Tag!
    		</audio>
    		
    		<div class="play" id="divAudio"><img id="play_image"> </div>
    		
    		</div>
    				
    </body>
      
    </html>
    &#13;
    &#13;
    &#13;

    P.S

    • 音频广告代码必须不是默认播放/暂停的标准广告。我使用了自己的播放器徽标,但在本例中,我使用绝对网址链接了徽标。

    • 我尝试使用其他帖子中的提示(multiple and dynamic audio players applied for a dictionary in HTML/JavaScript) 但那并没有那么好用。我试着用

      var audio = new Audio(); 和

      player.parentNode.insertBefore(audio,player.nextNode);

    解决问题1。 不确定,也许是因为没有使用标准播放器?

1 个答案:

答案 0 :(得分:1)

更新2

根据OP的要求,HTML5音频元素的原生控件被自定义暂停/播放按钮取代。我没有为每个音频添加一个事件监听器,而是使用了这个article中的技术。

  • handlePlay()(包含所有玩家的.arrayBox)上检测到点击时,系统会调用新功能<section>

  • handlePlay()将确定实际点击了哪些按钮,然后播放或暂停直接点击按钮后面的音频元素。

  • 添加了新的按钮对象ybtn,以便在生成音频元素之前生成。

    • 可以使用.btn类设置新按钮的样式。
    • 请注意,按钮的内容是字体:
      • ?&#128264; off
      • ?&#128266;
      • 此替代方案加载速度比图像快,而且还会减少HTTP请求。

Plunker

<强>段

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>DeXY Player</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=0" />
  <link href='https://fonts.googleapis.com/css?family=Raleway:600' rel='stylesheet' />
  <style>
    html {
      box-sizing: border-box;
      font: 500 16px/1.428 'Raleway';
      height: 100vh;
      width: 100vw;
    }
    
    *,
    *:before,
    *:after {
      box-sizing: inherit;
      margin: 0;
      padding: 0;
    }
    
    body {
      position: relative;
      font-size: 1rem;
      line-height: 1;
      height: 100%;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      -webkit-font-smoothing: antialiased;
      background: #222;
      color: #fc2;
    }
    
    button {
      font: inherit;
      line-height: 1.5;
      padding: 1px 3px;
      border-radius: 8px;
      border: 1px solid #00f;
      margin: 20px;
      background: rgba(0, 0, 0, .4);
      color: #00f;
      cursor: pointer;
    }
    
    button:hover {
      border: 1px solid #0ff;
      color: #0ff;
    }

    .btn {/* The audio buttons' styles */
      display: inline-block;
    }
  </style>
</head>

<body>
  <h1>DeXY Audio Array Player</h1>
  <button id="btn1"><a>Load</a></button>
  <section id="arrayBox">
    
  </section>
  <script>
//This array of strings is a required input needed to run DeXY Player.
 
    var playList = ['http://glpjt.s3.amazonaws.com/so/av/day01.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day02.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day03.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day04.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day05.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day06.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day07.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day08.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day09.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day10.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day11.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day12.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day13.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day14.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day15.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day16.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day17.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day18.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day19.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day20.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day21.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day22.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day23.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day24.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day25.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day26.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day27.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day28.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day29.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day30.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day31.mp3'];

//qty is the total quantity of elements within the playList array.

    var qty = playList.length;
    console.log('qty: ' + qty);
  </script>
  <script>
    var aBox = document.getElementById('arrayBox');
    var btn1 = document.getElementById('btn1');
//Click event triggers a callback: loadPlayers()
    aBox.addEventListener('click', handlePlay, false);
    btn1.addEventListener('click', loadPlayers, false);

    function loadPlayers() {
      var dArray = [];
//Each iteration creates a div#dx{?}.snd, appends it to the section, and then is pushed into dArray.

      for (var d = 0; d < qty; d++) {
        var division = document.createElement('div');
        division.id = "dx" + d;
        division.className = 'snd';
        aBox.appendChild(division);
        dArray.push(division);
      }
//Each iteration creates an audio element audio#x{?}, adds a series of attributes, and is assigned a MP3 from thr playlist.     
      
      for (var x = 0; x < qty; x++) {
        var ID = dArray[x].getAttribute('id');
        var xTag = document.createElement('audio');
        var yBtn = document.createElement('button');
        var xDiv = document.getElementById(ID);
        var xID = ID.substr(1, 3);
        var yID = ID.substr(2, 3);
        var xUrl = playList[x];
        
        xDiv.appendChild(yBtn);
        yBtn.setAttribute('id', 'y' + yID);
        yBtn.className ="btn";
        console.log('Player Button ID: '+ yBtn.id);
        yBtn.innerHTML = "&#128264;&nbsp;"; 
        yBtn.style.fontSize = "24px";
        yBtn.style.lineHeight = 1;

        xDiv.appendChild(xTag);
        xTag.setAttribute('id', xID);
        xTag.setAttribute('preload', 'auto');
        xTag.setAttribute('src', xUrl);
      }
    }
    
    function handlePlay(e) {
      if (e.target !== e.currentTarget) {
        var button = e.target.id;
        var btn = document.getElementById(button);
        console.log('button: '+btn);
        var clip = btn.nextSibling.id;
        console.log('clip: '+clip);
        var audio = document.getElementById(clip);
        console.log('audio '+audio);
        if(audio.paused) {
          audio.play();
          btn.innerHTML ="&#128266;"
          btn.style.color ="#0ff";
          btn.style.padding = '1px';
          btn.style.border = '1px solid #0ff';
        }
        else {
          audio.pause();
          btn.innerHTML ="&#128264;&nbsp;"
          btn.style.color ="#00f";
          btn.style.padding = '1px 5px';
          btn.style.border = '1px solid #00f';
        }
      }
      e.stopPropagation();
    }

  </script>
</body>

</html>

更新

在与OP进行简短讨论后,我更新了最新版本。此版本将接受并使用字符串数组作为播放列表。将所有内容重构为单个函数。单击该按钮,31个功能音频播放器会闪烁。 JS中的注释是函数loadPlayers()

的简单演练

Plunker

<强>段

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>dXPlayer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=0" />
  <link href='https://fonts.googleapis.com/css?family=Raleway:600' rel='stylesheet' />
  <style>
    html {
      box-sizing: border-box;
      font: 500 16px/1.428 'Raleway';
      height: 100vh;
      width: 100vw;
    }
    
    *,
    *:before,
    *:after {
      box-sizing: inherit;
      margin: 0;
      padding: 0;
    }
    
    body {
      position: relative;
      font-size: 1rem;
      line-height: 1;
      height: 100%;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      -webkit-font-smoothing: antialiased;
      background: #222;
      color: #fc2;
    }
    
    button {
      font: inherit;
      line-height: 1.5;
      padding: 1px 3px;
      border-radius: 8px;
      border: 1px solid #0ec;
      margin: 20px;
      background: rgba(0, 0, 0, .4);
      color: #0FF;
    }
  </style>
</head>

<body>
  <h1>dX Audio Array Player</h1>
  <section id="arrayBox">
    <button id="btn1">Load</button>
  </section>
  <script>
//This array of strings is a required input needed to run dXPlayer.
 
    var playList = ['http://glpjt.s3.amazonaws.com/so/av/day01.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day02.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day03.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day04.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day05.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day06.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day07.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day08.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day09.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day10.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day11.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day12.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day13.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day14.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day15.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day16.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day17.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day18.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day19.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day20.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day21.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day22.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day23.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day24.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day25.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day26.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day27.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day28.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day29.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day30.mp3', 'http://glpjt.s3.amazonaws.com/so/av/day31.mp3'];
    
//qty is the total quantity of elements within the playList array.

    var qty = playList.length;
    console.log('qty: ' + qty);
  </script>
  <script>
    var btn1 = document.getElementById('btn1');
//Click event triggers a callback: loadPlayers()

    btn1.addEventListener('click', loadPlayers, false);

    function loadPlayers() {
      var tgtArea = document.getElementById('arrayBox');
      var dArray = [];
//Each iteration creates a div#dx{?}.snd, appends it to the section, and then is pushed into dArray.

      for (var d = 0; d < qty; d++) {
        var division = document.createElement('div');
        division.id = "dx" + d;
        division.className = 'snd';
        tgtArea.appendChild(division);
        dArray.push(division);
      }
//Each iteration creates an audio element audio#x{?}, adds a series of attributes, and is assigned a MP3 from thr playlist.     
      
      for (var x = 0; x < qty; x++) {
        var ID = dArray[x].getAttribute('id');
        var xTag = document.createElement('audio');
        var xDiv = document.getElementById(ID);
        var xID = ID.substr(1, 3);
        var xUrl = playList[x];

        xDiv.appendChild(xTag);
        xTag.setAttribute('id', xID);
        xTag.setAttribute('controls', 'controls');
        xTag.setAttribute('preload', 'auto')
        xTag.setAttribute('src', xUrl);
      }
    }
  </script>
</body>

</html>

<小时/> <小时/>

OP的代码中有太多要调试,所以我提供的工作演示实现了与OP相同的目标。该演示包括:

  • 两个事件听众......
    • 加载DOM Content时的一个(JS几乎等同于jQuery的DOM Ready),以及......
    • 另一个按钮(btn1)点击。
  • 两个功能......
      触发loadPlayers()上的点击事件时,会调用
    • btn1
      • 它收集NodeList中的div.snd ...
      • ...然后转换为数组......
      • ...由for循环迭代。
      • 循环的每个实例都会生成一个加载了唯一内容的唯一音频元素。
    • xStruct是在loadPlayers()内调用的函数,用于执行克隆,添加属性和分配内容。

在准备这样的项目时,我更愿意将所有资产放在手边并且易于访问。   - 确保音频文件都在一个目录(文件夹)中。   - 使用连续编号的短功能文件名。 (例如wav1.wav,`wav2.wav等。)   - 以类似的方式分配ID。   - 如果您使用分散在多个位置的内容,使用冗长的详细名称并且具有无法轻松遵循模式的类和ID,则您将更容易出错和错误。

设置此演示时需要遵循一些事项:

  • 对于您想要创建的每个玩家,您必须在HTML中有一个div:

      除了数字之外,
    • ID应该相同。
    • 您还必须将班级.snd分配给每个div。
  • 以与div ID相同的方式命名每个文件。

Plunker

<强>段

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>35529918</title>
  <style>
    section {
      margin: 30px
    }
  </style>
</head>

<body>
  <button id="btn1">Load</button>
  <section>
    <div id="wav1" class="snd"></div>
    <div id="wav2" class="snd"></div>
    <div id="wav3" class="snd"></div>
  </section>
  <script>
    window.addEventListener('DOMContentLoaded', function(e) {

      var btn1 = document.getElementById('btn1');

      btn1.addEventListener('click', loadPlayers, false)

      function loadPlayers() {
        var divList = document.querySelectorAll('.snd');
        var divArray = Array.prototype.slice.call(divList);
        for (var i = 0; i < divArray.length; i++) {
          var ID = divArray[i].id;
          xStruct(ID);
        }
      }

      function xStruct(ID) {
        var xTag = document.createElement('audio');
        var xDiv = document.getElementById(ID);
        var xUrl = 'https://glpjt.s3.amazonaws.com/so/av/';
        var xWav = xUrl + ID + '.wav';
        var xID = ID.substr(1, 3);
        xDiv.appendChild(xTag);
        xTag.setAttribute('id', xID);
        xTag.setAttribute('controls', 'controls');
        xTag.setAttribute('src', xWav);
      }
    }, false);
  </script>
</body>

</html>