【问题标题】:Playing audio sound everytime an element is pushed in array每次将元素推入数组时播放音频声音
【发布时间】:2018-01-28 16:44:57
【问题描述】:

我有一个名为primeFactors 的函数,我尝试在其中找到作为某个n 数的除数的所有数,但同时它们也必须是质数。在某种意义上只是一个基本的算法。

在这样做的同时,我还认为放置每次while 语句循环通过块时播放的音频声音会很有趣(只是为了它)。然而,声音只播放一次,即使有时结果是由 3 个因素组成的数组(例如[2, 7, 11])。在这种情况下,我希望在将每个元素推入数组之前播放三遍声音。这是我的代码:

function primeFact(n) {
    let factors = [];
    let divisor = 2;
    let clap = new Audio('clap.mp3');

    while (n > 2) {
        if (n % divisor == 0) {
            clap.currentTime = 0;
            clap.play();
            factors.push(divisor);
            n = n / divisor;
        } else {
            divisor++;
        }
    }
    return factors;
}

【问题讨论】:

  • 要等播放完再播放第二遍吗?
  • @SLaks 是的,那很好。

标签: javascript algorithm primes


【解决方案1】:

您可以使用队列。声音只播放一个,因为在那个循环中它几乎是瞬时的。这有效:

<script>
var sounds = new Array,
    clap = new Audio('clap.mp3'); // no need to assign it every time
function primeFact(n) {
    let factors = [];
    let divisor = 2;

    while (n > 2) {
        if (n % divisor == 0) {
            clap.currentTime = 0;
            sounds.push(clap); // add sound to queue
            factors.push(divisor);
            n = n / divisor;
        } else {
            divisor++;
        }
    }
    playQueuedSounds(); // play all sounds added
    return factors;
}
function playQueuedSounds() {
    if (sounds.length === 0) return;
    var sound = sounds.pop(); // get last sound and remove it
    sound.play();
    sound.onended = function() { // go look at the queue again once current sound is finished
        playQueuedSounds();
    };
}
primeFact(25); // two clap noises :)
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多