SourceDataLine在OpenJDK-11上不起作用

时间:2018-10-20 21:20:42

标签: java linux audio javasound pulseaudio

我编写了一个使用Java声音库类SourceDataLine的程序。

我已经在Linux Mint 19上使用openjdk 8编写了它,而使用了脉冲音频。

然后我切换到openjdk 11,尽管它运行无误,但没有声音输出。

一旦我切换回openjdk 8,声音就会再次起作用。

我不认为问题出在代码内,但无论如何都在这里。这很简单。它只是起到一些白噪声作用。

import java.io.*;
import javax.sound.sampled.*;

/**
 * SourcDataLineTest
 */
public class SourceDataLineTest {

final int bytesPerSmp = 2;

final int smpRate = 48000;
final int bitsPerSmp = bytesPerSmp * 8;
final int channels = 1;
final int framesSizeInBytes = bytesPerSmp * channels;
final int frameRate = (int)smpRate;
final boolean isBigEndian = false;
final int bufferSizeInBytes = 2048;

private SourceDataLine line;
boolean mStarted;

private byte[] mPrime;

public SourceDataLineTest () 
{
    try {
        AudioFormat af = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED , smpRate, bitsPerSmp, channels, framesSizeInBytes, frameRate, isBigEndian);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
        line = (SourceDataLine) AudioSystem.getLine(info);
        line.open(af, bufferSizeInBytes);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    float[] fPrime = new float[32168];
    mPrime = new byte[fPrime.length * bytesPerSmp];
    AudUtil.floatAudioToByte(fPrime, mPrime, bytesPerSmp);
}

void writeToLine(byte[] buffer)
{
    int position = 0;
    while (position < buffer.length) {
        int len = line.available();
        if (position + len >= buffer.length)
            len = buffer.length - position;
        line.write(buffer , position , len);
        position += len;

        if (!mStarted && line.available() == 0)
            line.start();
    }
}

void play()
{
    assert !mStarted;

    // generate while noise
    float[] data = new float[32768];
    AudUtil.generateWhiteNoise(data);

    // convert to bytes
    byte[] byteData = new byte[data.length * bytesPerSmp];
    AudUtil.floatAudioToByte(data , byteData, bytesPerSmp);

    // play a bunch of whitenoise
    for (int i = 0; i < 40; i++)
        writeToLine(byteData);

    mStarted = false;
    line.stop();
}

void close() {
    assert !mStarted;
    line.close();
}

}

0 个答案:

没有答案