java - 使用 Java 源数据线进行音频时出现爆音/爆裂声

标签 java debugging audio javasound

我在使用 Java 源数据行时遇到问题。我需要演奏一个音调,所以我创建了一个仅代表音调的 Tone 类。一切工作正常,除了当我播放声音时,扬声器在声音开始时弹出。有没有什么办法解决这一问题?它用于一个研究项目,需要在没有噼啪声的情况下运行,因为这可能会影响结果。源代码如下。谢谢!

package edu.jhu.halberda.audiopanamath;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JOptionPane;

public class Tone {
public enum Channel {
    LEFT, RIGHT, STEREO
};

public static final float SAMPLE_RATE = 44104; // Should be a multiple of 8
protected byte[] buf;
protected int hz, msecs;
protected double vol;
protected Channel channel;

Tone() {
} // necessary so that subclasses don't complain

public Tone(int hz, int msecs, double vol, Tone.Channel channel) {
    if (hz <= 0)
        throw new IllegalArgumentException("Frequency <= 0 hz");
    if (msecs <= 0)
        throw new IllegalArgumentException("Duration <= 0 msecs");
    if (vol > 1.0 || vol < 0.0)
        throw new IllegalArgumentException("Volume out of range 0.0 - 1.0");
    this.channel = channel;
    this.hz = hz;
    this.vol = vol;
    this.msecs = msecs;
    generateTone();

}

private void generateTone() {
    int len = (int)Math.ceil((2 * SAMPLE_RATE * msecs / 1000.0d));
    if (len % 2 == 1)
        len = len + 1;
    buf = new byte[len];
    for (int i = 0; i < buf.length /2; i++) {
        double angle = (i * hz / SAMPLE_RATE) * 2.0 * Math.PI;
        buf[2*i + 1] = buf[2*i] = (byte) Math.round(Math.sin(angle) * 127.0 * vol);
    }
}

public void play(SourceDataLine sdl) { // takes an opened SourceDataLine
    FloatControl panControl = (FloatControl) sdl
            .getControl(FloatControl.Type.PAN);
    if (panControl != null) { // Preferred method using built in sound
                                // control, but not guaranteed to be
                                // available
        if (channel == Channel.LEFT) {
            panControl.setValue(-1);
        } else if (channel == Channel.RIGHT) {
            panControl.setValue(1);
        } else {
            panControl.setValue(0);
        }
    } else { // fallback method is directly manipulates the buffer
        if (channel != Channel.STEREO) {
            int nSilenceOffset;
            byte nSilenceValue = 0;
            if (channel == Channel.LEFT) {
                nSilenceOffset = 1;
            } else {
                nSilenceOffset = 0;
            }
            for (int i = 0; i < buf.length; i += 2) {
                buf[i + nSilenceOffset] = nSilenceValue;
            }
        }

    }
    sdl.write(buf, 0, buf.length);
    sdl.drain();
}

public static void main(String[] args) {
    AudioFormat af = new AudioFormat(Tone.SAMPLE_RATE, 8, 2, true, false);
    SourceDataLine sdl;
    try {
        sdl = AudioSystem.getSourceDataLine(af);
    } catch (LineUnavailableException e) {
        JOptionPane.showMessageDialog(null, "Couldn't get sound line");
        return;
    }
    try {
        sdl.open(af);
    } catch (LineUnavailableException e) {
        JOptionPane.showMessageDialog(null, "Couldn't open sound line");
        return;
    }
    sdl.start();
    Tone left = new Tone(400, 2000, .5, Tone.Channel.LEFT);
    System.out.println("Playing left");
    long t = System.currentTimeMillis();
    left.play(sdl);
    System.out.println(System.currentTimeMillis()-t);
    System.out.println("Finished left");
    Tone right = new Tone(400, 2000, .5, Tone.Channel.RIGHT);
    System.out.println("Playing right");
    right.play(sdl);
    System.out.println("Finished right");
    sdl.stop();
    sdl.close();
}

}

最佳答案

尝试这个变体,它使用粗略的淡入/淡出效果。

private void generateTone() {
    int len = (int)Math.ceil((2 * SAMPLE_RATE * msecs / 1000.0d));
    if (len % 2 == 1)
        len = len + 1;
    buf = new byte[len];
    int fadeCount = 1600;
    for (int i = 0; i < buf.length /2; i++) {
        double fadeRate = 1.0;
        double angle = (i * hz / SAMPLE_RATE) * 2.0 * Math.PI;
        if (i<fadeCount) {
            fadeRate = (double)i/(double)fadeCount;
        } else if (i>(buf.length/2)-fadeCount) {
            int bufLength = buf.length;
            int buf = bufLength/2;
            int countDown = buf-i;
            fadeRate = (double)countDown/(double)(fadeCount);
        }
        buf[2*i + 1] = buf[2*i] = (byte) Math.round(
            Math.cos(angle) * 127.0 * vol * fadeRate);
    }
}

关于java - 使用 Java 源数据线进行音频时出现爆音/爆裂声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630324/

相关文章:

列表的Java 8范围()?

java - 单击鼠标添加图像? Java小程序

c - 无法检测到第二次机会异常?

android - Eclipse 未检测到索尼爱立信 Xperia 进行调试?

c# - 构建器模式实现 C# vs. JAVA

java - 重用 StringBuffer

debugging - 如何调试 Ansible 包含和依赖项?

c# - 错误的 .wav 格式录制音频 NAudio 库

javascript - getUserMedia() 音频 block 摄像头

ios - iPhone 应用程序中的混响效果