2015-01-02 4 views
-3

эй, поэтому у меня есть массив с 8 звуками в нем, и сейчас у меня это есть, поэтому, когда я нажимаю на изображение, случайный звук из массива играет, его перемещают в новый массив , и когда исходный массив звуков пуст, новый массив передаст песни обратно в исходный массив.Переместить случайный элемент из одного массива в другой

-the problem is that when it removes the sound its not the sound that was just played.

-also id like to make clicking on the image multiple times not do anything other than playing the one sound until it finishes(then its moved to the empty array),then you can click the image for a new random sound

var sounds = [ 
"https://evolution.voxeo.com/library/audio/prompts/numbers/1.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/2.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/3.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/4.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/5.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/6.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/7.wav", 
"https://evolution.voxeo.com/library/audio/prompts/numbers/8.wav" 
]; 

var oldSounds = []; 

function playSound() 
{ 
var randomSound = sounds[Math.floor(Math.random() * sounds.length)]; 

document.getElementById("player").innerHTML= 
"<embed src=\""+randomSound+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; 

//splice randomSound from sounds array into var removed 
//than push that sound into oldSounds array 
var removed = sounds.splice(randomSound, 1); 
oldSounds.push(removed); 
console.log("==song removed from sound array = " + removed); 
console.log(" .sounds length = " + sounds.length); 
console.log(" .oldSounds length = " + oldSounds.length); 

//if all sounds played from sound array AND all sounds are now in oldSounds array 
//than move the sounds from oldSounds to sounds 
if (sounds.length === 0 && oldSounds.length === 8) 
{ 
    console.log("----------------"); 
    sounds = oldSounds; 
    console.log("sounds length = " + sounds.length); 
    oldSounds = []; 
    console.log("oldSounds length = " + oldSounds.length); 
    console.log("----------------"); 
} 
} 

это то, что я до сих пор: http://jsbin.com/sekajumeva/1/edit?html,js,console,output

любая помощь будет оценена. Благодарю.

+2

какой-то код будет лучше? не просто jsbin? – Mritunjay

+2

Пожалуйста, подумайте о лучшем названии. – alex

ответ

0

Насколько я знаю, splice() принимает index как первый параметр, и вы передаете звуковой url.

Чтобы исправить код, преобразовать это:

var removed = sounds.splice(randomSound, 1); 

в этом:

var removed = sounds.splice(sounds.indexOf(randomSound), 1); 

Я не проверял, потому что честно говоря, я не могу здесь ни звука, но посмотрите, что работает, с новым годом!

+0

Я просто пытался быть приятным, хотя :) – undefined

+0

Достаточно честный. Я удалю другой комментарий.Что касается ответа, конечно, вы правы, но я бы предложил сохранить индекс в переменной в точке, где генерируется случайное число. – nnnnnn

+0

Это okey, с новым годом! – undefined

0

Так что ваш код:

var sounds = [ 
    "https://evolution.voxeo.com/library/audio/prompts/numbers/1.wav", 
    "https://evolution.voxeo.com/library/audio/prompts/numbers/2.wav", 
    ... 
]; 

var oldSounds = []; 

function playSound() 
{ 
    var randomSound = sounds[Math.floor(Math.random() * sounds.length)]; 

Так randomSound будет что-то вроде "https://evolution.voxeo.com/library/audio/prompts/numbers/2.wav". Тогда:

document.getElementById("player").innerHTML= 
    "<embed src=\""+randomSound+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; 

    //splice randomSound from sounds array into var removed 
    //than push that sound into oldSounds array 
    var removed = sounds.splice(randomSound, 1); 

Первый аргумент сплайсинга должен быть индексом (0, 1, 2, и т.д.), но вы передавая выше строку. Это будет преобразовано в 0 (см. Array.prototype.splice step 5), поэтому вы просто сохраните сплайсинг первого члена массива.

Было бы лучше, чтобы сделать что-то вроде:

var indexToPlay = Math.floor(Math.random() * sounds.length); 
var randomSound = sounds[indexToPlau]; 

... 

var removed = sounds.splice(indexToPlay, 1); 
1

проблема должна исходит от splice.
он возвращает массив, когда вы нажимаете на oldSounds, это будет массив в массиве, который не то, что вы хотите? Правильным может быть >>

var removed = sounds.splice(randomSound, 1); 
oldSounds.push(removed[0]); 

вопрос номер 2, вы можете сделать переменную, чтобы сохранить состояние.
например, состояние playing. Инициировать состояние по умолчанию false как var isPlaying = false. то в вашем playSound() fiunction вы проверите состояние, если оно воспроизводится, просто вернитесь. if (isPlaying) {return;} else {isPlaying = true} .. помню в конце функции playSound, установите флаг назад к ложному isPlaying= false

var isPlaying = false; 
function playSound() { 
    if (isPlaying) { 
    return; 
    } 
    isPlaying = true; // set the state to true, if using click the image again, this function will not be called because returned on the `if` on top 

    // ur original codes 
    var randomSound = sounds[Math.floor(Math.random() * sounds.length)]; 
    document.getElementById("player").innerHTML= 
    "<embed src=\""+randomSound+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; 

    .... 
    isPlaying = false; // set the state back to false, so the music will be played 
} 
+0

Это часть проблемы, хороший улов. – RobG

+0

отлично это помогает :) просто добавила мою личную рекомендацию по второму вопросу. – ChinKang

+0

так что бы я установил isPlaying? Если его document.getElementById («player») .... как бы установить значение isPlaying? – user4411473

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