1

我在 stackoverflow 上发现了这段代码,它会慢慢淡出音轨。它运作良好。它的结构我发现在不复制和粘贴的情况下很难重复使用,因为该函数在其自身内部调用自身。这是代码:

function fadeVolume(volume, callback) {
    //change the volume by factor each time
    //will check if setTimeout is used to loop as well as wait, as it seems so here
    var factor = 0.02,
        speed = 50;
    if (volume > factor) {
        setTimeout(function () {
            fadeVolume((gameController.myAudio.preGameTrack.volume -= factor), callback);
        }, speed);
    } else {
        (typeof (callback) !== 'function') || callback();
    }
};
fadeVolume(gameController.myAudio.preGameTrack.volume, function () {
    preGameContent.ready = true;
    //stop the music altogether
    gameController.myAudio.preGameTrack.pause();
    gameController.myAudio.preGameTrack.currentTime = 0;
})
4

1 回答 1

2

除了gameController.myAudio.preGameTrack.

将其存储在变量中并传入..如果您在该上下文中交谈,应该可以重用。

function fadeVolume(track, factor, speed, callback) {
    //change the volume by factor each time
    //will check if setTimeout is used to loop as well as wait, as it seems so here

    if (track.volume > factor) {
        setTimeout(function () {
            fadeVolume((track.volume -= factor), callback);
        }, speed);
    } else {
        (typeof (callback) !== 'function') || callback();
    }
};

var track = gameController.myAudio.preGameTrack,
    factor = 0.2,
    speed = 50;
fadeVolume(track, factor, speed, function () {
    preGameContent.ready = true;
    //stop the music altogether
    track.pause();
    track.currentTime = 0;
})
于 2013-08-02T03:03:04.020 回答