2015-09-07 3 views
0

Я хотел бы расширить вопрос, который я задал не давно: enter link description hereмногочисленных и динамические аудиоплеер применяются для словаря в HTML/JavaScript

Как и прежде, я также пытаюсь написать HTML/JavaScript-файл, который будет воспроизводить звук животных (.mp3) в соответствии с данным названием животного.

Только здесь, если пользователь вводит имя определенного животного, имеющего множество звуков, тогда результатом будет множество аудиоплееров (тегов) на выбор.

Например, если для ввода есть только один результат, например, пример «коровы», то это не проблема, он печатает только коровы и позволяет использовать звук только для коровы. До сих пор все вышеупомянутые работы!

Но если пользователь вводит «Птицу» в поле, программа выполняет поиск в массиве (словаре). Если он существует в массиве, он печатает разные виды птиц («Черная птица», «Воробей», «Кукушка») и позволяет использовать звук для каждого из них в разных аудиоплеерах. Конечно, он должен быть динамичным и соответствовать 2, 4, 5 или любым другим результатам.

Так вот что я пытаюсь выяснить - как разрешить несколько звуковых тегов для каждого элемента (значения), приписываемого одному и тому же ключу. То есть, если для «Птицы» есть 3 значения: «Блэкберд», «Воробей» и «Кукушка», то для каждого должен появиться отдельный тег аудиоплеера.

как в этом примере:

-Blackbird -> аудиоплеера tag1 (играет Blackbird.mp3)

-Cuckoo -> аудиоплеера tag2 (играет Cuckoo.mp3)

-Sparrow -> аудиоплеер tag3 (играет Sparrow.mp3)

/

Вот опять упрощенная картина (но только один аудио теге ..) для этого примера и JavaScript/HTML ниже:

Я был бы очень признателен за любую помощь! Заранее спасибо!

enter image description here

var animal_sub = {"Bird":"- (Blackbird) "+"\n "+"- (Cuckoo) "+ "\n "+"- (Sparrow) " 
 
}; 
 

 
function animalVoice(){ 
 
    // Get the names from the text field 
 
    theAnimal=document.animals.newAnimal.value; 
 
    if(theAnimal in animal_sub) { 
 
     document.animals.outAnimal.value=animal_sub[theAnimal]; //printing the word in the textarea 
 
     var line=animal_sub[theAnimal];      
 
     regex=line.match(/\(([^\)]*)\)/g);    //finds what's in the() and puts it in ARRAY using regular ex. 
 
     document.getElementById("myPlayer").src = "audio/animals/" + regex[0].substring(1,regex[0].length-1) + ".mp3"; //executes audio for the first appeared index (regex[0]) 
 
     } 
 
    else if(!(theAnimal in animal_sub)) { 
 
    theAnimal=document.animals.newAnimal.value; 
 
    document.animals.outAnimal.value=theAnimal; 
 
    document.getElementById("myPlayer").src = "audio/animals/" + theAnimal + ".mp3"; //if the animal is NOT in the array, it simply prints it and plays the audio 
 
    } 
 
     
 
};
<!DOCTYPE html> 
 
<html 
 
    <head> 
 
    <script type="text/javascript" src="animal_voices.js"></script> 
 
    </head> 
 
    <body> 
 
     <p>please enter the animal's name here: </p> 
 
     <form name="animals"> 
 
     <input type="text" name="newAnimal" size ="30" /> 
 
     <input type="button" name="animal" value="find the sound" 
 
     onclick="animalVoice();"> 
 
     <br/> 
 
     <h4>output:</h4> 
 
     <textarea cols = "31" rows = "4" name="outAnimal"> 
 
     </textarea> 
 
     <audio 
 
      src="audio/animals/" 
 
      id="myPlayer" 
 
      preload="auto" 
 
      controls>  
 
     </audio>  
 
     </form> 
 
</body> 
 
</html>

ответ

1

Вы урожденная d, чтобы вставить Arrays в ваш dictionnary (animal_sub объект).
Тогда, если возвращенный объект является массивом, перебирайте все его ключи и добавьте столько новых аудио, сколько необходимо.
Примечание: чтобы определить, является ли объект массивом, я использую метод Array.isArray(), который, к сожалению, не поддерживался старыми браузерами (IE8-). Вы можете найти some polyfills.

var animal_sub = {"Bird":["Blackbird", "Cuckoo","Sparrow"], "Fish":"Sardine"}; 
 

 
function animalVoice(){ 
 
    var multiAud = document.querySelectorAll('.multiple_audio'); 
 
    // remove the added audio players 
 
    for(var i=0; i<multiAud.length; i++){ 
 
     multiAud[i].parentNode.removeChild(multiAud[i]); 
 
     } 
 
    // Keep some references of our elements 
 
    var player = document.getElementById("myPlayer"); 
 
    var output = document.animals.outAnimal; 
 
    var theAnimal=document.animals.newAnimal.value; 
 
    // if the input value is in the Dictionnary 
 
    if(theAnimal in animal_sub) { 
 
     var animal = animal_sub[theAnimal]; 
 
     // reset the textArea 
 
     output.value=''; 
 
     // if our object is an Array 
 
     if(Array.isArray(animal)){ 
 
     
 
     for(var i=0; i<animal.length; i++){ 
 
      output.value+=animal[i]+'\n'; 
 
      // if it's the first in the array 
 
      if(i<1){ 
 
      player.src= "audio/animals/" + animal[i] + ".mp3"; 
 
      } 
 
      else { 
 
      // create a new Audio 
 
      var audio = new Audio("audio/animals/" + animal[i] + ".mp3"); 
 
      // add a class so that we can delete it on next call 
 
      audio.className = 'multiple_audio'; 
 
      audio.controls=true; 
 
      // insert it in the document 
 
      player.parentNode.insertBefore(audio, player.nextNode); 
 
      } 
 
      } 
 
     } 
 
     // it's not an Array 
 
     else if(typeof animal === 'string'){ 
 
     output.value = animal; 
 
     player.src = "audio/animals/" + animal + ".mp3"; 
 
     } 
 
     } 
 
    else { // if (!(theAnimal in animal_sub)) { 
 
     output.value = theAnimal; 
 
     // are you sure you want to do it ? 
 
     player.src = "audio/animals/" + theAnimal + ".mp3"; 
 
    } 
 
     
 
};
<!DOCTYPE html> 
 
<html 
 
    <head> 
 
    <script type="text/javascript" src="animal_voices.js"></script> 
 
    </head> 
 
    <body> 
 
     <p>please enter the animal's name here: </p> 
 
     <form name="animals"> 
 
     <input type="text" name="newAnimal" size ="30" /> 
 
     <input type="button" name="animal" value="find the sound" 
 
     onclick="animalVoice();"> 
 
     <br/> 
 
     <h4>output:</h4> 
 
     <textarea cols = "31" rows = "4" name="outAnimal"> 
 
     </textarea> 
 
     <audio 
 
      src="audio/animals/" 
 
      id="myPlayer" 
 
      preload="auto" 
 
      controls>  
 
     </audio>  
 
     </form> 
 
</body> 
 
</html>

+0

Вот что я искал! большое спасибо! – Apython

1

Если я правильно понимаю ваш вопрос:

//var animal_sub = {"Bird":"- (Blackbird) "+"\n "+"- (Cuckoo) "+ "\n "+"- (Sparrow) " 
 
// }; 
 

 
var animal_sub = { 
 
    bird: [ 
 
     'Blackbird', 'Cuckoo', 'Sparrow' 
 
    ] 
 
} 
 

 
function animalVoice(){ 
 
    // Get the names from the text field 
 
    theAnimal=document.animals.newAnimal.value; 
 
    
 
    if(theAnimal in animal_sub) { 
 
     var result = animal_sub[theAnimal]; 
 
     document.animals.outAnimal.value=result.join(','); //printing the word in the textarea 
 
     for(var i = 0; i < result.length; i++) { 
 
     var a = document.createElement('audio'); 
 
     document.body.appendChild(a); 
 
     a.setAttribute('src', 'audio/animals/' + result[i]); 
 
     a.setAttribute('controls', 'controls'); 
 
     } 
 
    } 
 
};
<p>please enter the animal's name here: </p> 
 
<form name="animals"> 
 
<input type="text" name="newAnimal" size ="30" value="bird" /> 
 
<input type="button" name="animal" value="find the sound" 
 
onclick="animalVoice();"> 
 
<br/> 
 
<h4>output:</h4> 
 
<textarea cols = "31" rows = "4" name="outAnimal"> 
 
</textarea> 
 
<!--<audio 
 
    src="audio/animals/" 
 
    id="myPlayer" 
 
    preload="auto" 
 
    controls>  
 
</audio>--> 
 
</form>

+0

Да вы получили вопрос и при условии хорошего альтернативного ответа! Спасибо!! – Apython

Смежные вопросы