java声音淡出

Posted

技术标签:

【中文标题】java声音淡出【英文标题】:java sound fade out 【发布时间】:2009-01-22 22:31:34 【问题描述】:

使用 javax.sound.sampled,我想淡出我开始无限循环的声音。这就是我开始声音的方式:

Clip clip = Audiosystem.getClip();
AudioInputStream inputStream = AudioSystem
.getAudioInputStream(new File("x.wav"));
clip.open(inputStream);
clip.loop(clip.LOOP_CONTINUOUSLY);

谁能指出我该怎么做?我是否应该使用不同的声音系统,例如 FMOD(如果这在 Java 中可行)?谢谢。

【问题讨论】:

【参考方案1】:

看看这里:Openjava sound demo 他们使用FloatControl gainControl; // for volume

/**
 * Set the volume to a value between 0 and 1.
 */
public void setVolume(double value) 
    // value is between 0 and 1
    value = (value<=0.0)? 0.0001 : ((value>1.0)? 1.0 : value);
    try 
        float dB = (float)(Math.log(value)/Math.log(10.0)*20.0);
        gainControl.setValue(dB);
     catch (Exception ex) 
        ex.printStackTrace();
    



/**
 * Fade the volume to a new value.  To shift volume while sound is playing,
 * ie. to simulate motion to or from an object, the volume has to change
 * smoothly in a short period of time.  Unfortunately this makes an annoying
 * clicking noise, mostly noticeable in the browser.  I reduce the click
 * by fading the volume in small increments with delays in between.  This
 * means that you can't change the volume very quickly.  The fade has to
 * to take a second or two to prevent clicks.
 */
float currDB = 0F;
float targetDB = 0F;
float fadePerStep = .1F;   // .1 works for applets, 1 is okay for apps
boolean fading = false;

public void shiftVolumeTo(double value) 
    // value is between 0 and 1
    value = (value<=0.0)? 0.0001 : ((value>1.0)? 1.0 : value);
    targetDB = (float)(Math.log(value)/Math.log(10.0)*20.0);
    if (!fading) 
        Thread t = new Thread(this);  // start a thread to fade volume
        t.start();  // calls run() below
    


/**
 * Run by thread, this will step the volume up or down to a target level.
 * Applets need fadePerStep=.1 to minimize clicks.
 * Apps can get away with fadePerStep=1.0 for a faster fade with no clicks.
 */
public void run()

    fading = true;   // prevent running twice on same sound
    if (currDB > targetDB) 
        while (currDB > targetDB) 
            currDB -= fadePerStep;
            gainControl.setValue(currDB);
            try Thread.sleep(10); catch (Exception e) 
        
    
    else if (currDB < targetDB) 
        while (currDB < targetDB) 
            currDB += fadePerStep;
            gainControl.setValue(currDB);
            try Thread.sleep(10); catch (Exception e) 
        
    
    fading = false;
    currDB = targetDB;  // now sound is at this volume level

【讨论】:

以上是关于java声音淡出的主要内容,如果未能解决你的问题,请参考以下文章

淡入/淡出声音

初学者 python 编程帮助交叉淡入淡出声音

Audiokit 交叉淡入淡出声音循环

A-Frame:如何提供声音淡出以消除声音终止时的音频点击

开始播放时声音随机中断

使用javascript淡入/淡出播放/暂停音乐