ごらくらいふ

プログラミングしたりゲームしたり

Audioオブジェクトでフェードイン

フェードアウトがあればフェードインも必要。

yajamon.hatenablog.com

環境

chrome 44.0.2403.130 m (64-bit)

example

一定間隔でフェードイン

volume = 0 + a*frame

music = new Audio();
music.src = "your/music/path.mp3";

music.fadeTimerId = null;
music.fadeIn = function (time) {
    var frameRate = 30;
    var frameCount = 0;
    var endFrame = time * frameRate;
    var frameSecond = 1/frameRate;

    var start = 0;
    var step  = 1 / (endFrame);
    
    this.volume = start;
    this.play();
    
    var that = this;
    that.fadeTimerId = setInterval(function(){
        var nextVolume = start + step*frameCount ;
        if (nextVolume >= 1) {
            clearInterval(that.fadeTimerId);
            that.volume = 1;
            return;
        }
        that.volume = nextVolume;
        ++frameCount;
    },frameSecond * 1000);
}

グッとフェードイン

volume = 0 + a*frame2

music = new Audio();
music.src = "your/music/path.mp3";

music.fadeTimerId = null;
music.fadeIn = function (time) {
    var frameRate = 30;
    var frameCount = 0;
    var endFrame = time * frameRate;
    var frameSecond = 1/frameRate;

    var start = 0;
    var step  = 1 / (endFrame*endFrame);
    
    this.volume = start;
    this.play();
    
    var that = this;
    that.fadeTimerId = setInterval(function(){
        var nextVolume = start + step*frameCount*frameCount ;
        if (nextVolume >= 1) {
            clearInterval(that.fadeTimerId);
            that.volume = 1;
            return;
        }
        that.volume = nextVolume;
        ++frameCount;
    },frameSecond * 1000);
}