Java SourceDataLine 未在第一个缓冲区结束时调用更新

标签 java audio libgdx

问题的简化版本:即使我之前已经让它工作了,这个试图用 javax.sound.sampled.SourceDataLine 制造一些噪音的代码在第一个缓冲区为空后不会调用更新。

编辑:更新了 16 位立体声的代码。
调用 Output.open(format,buffersize) 时定义的样本数量播放声音。

将代码示例提炼为两个类项目:

package javaxaudiotest;

import java.io.IOException;

public class JavaxAudioTest {

    public static void main(String[] args) throws IOException {
        JavaxAudioDevice audio = new JavaxAudioDevice();
        audio.create();
        System.out.println("Hit enter to quit.");
        int c = 'a';
        while (c != '\n') {
            c = System.in.read();
        }

        audio.dispose();
    }

}

带有 libGDX 的 JavaxAudioDevice 和我自己的项目特定的东西被取出。
package javaxaudiotest;

import java.util.Arrays;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.SourceDataLine;

public class JavaxAudioDevice implements LineListener {

    byte[] byteBuf = null;

    boolean quit = false;
    boolean hasquit = false;
    boolean underflow = false;

    SourceDataLine Output;
    int leader = 1024;
    boolean notDoneYet = false;
    boolean alreadyLead = false;
    byte b = 0;


    public int create() {
        quit = false;
        AudioFormat af = new AudioFormat(44100, 16, 2, true, false);
        try {
            Output = AudioSystem.getSourceDataLine(af);
        } catch (Exception e) {
            System.err.println("Failed to create audio device. " + e.getLocalizedMessage());
            return 1;
        }

        if (Output != null) {
            Output.addLineListener(this);
            try {
                Output.open(af,44100*8);
            } catch (Exception e) {
                System.err.println("Failed to open audio device. " + e.getLocalizedMessage());
                return 2;
            }
        }
        System.err.println("Created JavaxAudioDevice");
        while (!Output.isOpen());
        update(null);
        System.err.println(Output.getFormat().toString());
        return 0;
    }


    public void dispose() {
        quit = true;
        Output.close();
        Output.flush();
        Output = null;
        hasquit = true;
    }

//LineListener
    @Override
    public void update(LineEvent le) {
        if (le == null) System.err.println("Audio update");
        else System.err.println("Audio update " + le.toString());

        if ( !quit && ( le == null || le.getType() == LineEvent.Type.STOP ) ) {
            boolean uf = false;
            while (notDoneYet) {
                uf = true;
            }
            notDoneYet = true;
            if (uf) {
                underflow = true;
                System.err.println("underflow");
            }

            if (byteBuf == null) { //insert some leader tape
                short[] shortBuf = new short[44100*8];
                for (int i = 0; i < shortBuf.length; i+=2) {
                    shortBuf[i] = (short)((b++)*50);
                    shortBuf[i+1] = (short)((b++)*200);
                }

                byteBuf = new byte[shortBuf.length * 2];
                for (int i = 0; i < byteBuf.length; ++i) {
                    //little endian
                    if (i % 2 == 0) byteBuf[i] = (byte) (shortBuf[i / 2]); //low byte
                    else byteBuf[i] = (byte) (shortBuf[i / 2] >> 8); //high byte
                }
            }
            Output.write(byteBuf, 0, byteBuf.length);
            Output.start();
            byteBuf = null;
            if (!Output.isRunning()) { //debug
                System.err.println("Output not running");
            } else {
                System.err.println("Output running");
            }

            short[] shortBuf = new short[44100*8];
            for (int i = 0; i < shortBuf.length; i+=2) {
                    if (i%2 == 0) shortBuf[i] = shortBuf[i+1] = (short)((b++)*100);
                    else shortBuf[i] = shortBuf[i+1] = (short)((b++)*150);
            }

            byteBuf = new byte[shortBuf.length * 2];
            for (int i = 0; i < byteBuf.length; ++i) {
                //little endian\
                if (i % 2 == 0) byteBuf[i] = (byte) (shortBuf[i / 2]); //low byte
                else byteBuf[i] = (byte) (shortBuf[i / 2] >> 8); //high byte
            }

            notDoneYet = false;
        }

    }
}

这是一些示例输出:
run:
Created JavaxAudioDevice
Audio update Open event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@4cac0ef5
Audio update
Output running
Audio update Start event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@4cac0ef5
Hit enter to quit.
PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian

Audio update Stop event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@4cac0ef5
Audio update Close event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@4cac0ef5
BUILD SUCCESSFUL (total time: 7 seconds)

编辑:我用锯齿生成循环的副本替换了“引导带”。我还将 byteBuf 初始化为 null,以便激活该部分。此外,我添加了一个循环来等待线路打开以强制第一次更新。现在我的耳朵里出现了几分之一秒的锯齿波。但是,仍然不会自动更新。

下面的原始问题:

我正在使用 libGDX 并且我编写了一些代码来使一些声音与主线程异步。然后我将 libGDX 自己的 AsyncExecutor 用于几个线程,将 AudioDevice 用于音频。 AudioDevice.write(short[],int,int) 被阻塞,所以我需要在另一个线程中执行它。这是成功的。不幸的是,它有时会卡顿(总是从 netbeans 运行时)。例如,当我运行 gradle 任务 :desktop:dist 时,它会生成一个完整的 jar 文件,而在 Windows 10 下运行时,它就像一个铃铛一样清晰。

因此,我正在使用 javax.sound.sampled 即 SourceDataLine 制作 pcm 输出的桌面特定实现。所以我创建了一个类来启动声音并充当 SourceDataLine 的监听器。该类位于桌面子项目中,并在创建主类时传递给核心子项目。它实现了一个小接口(interface),它是核心的一部分。我将其设置为 16 位签名立体声 pcm。我在核心中有一个类,它生成一个方波并返回一个短裤数组。

这就是问题所在:我什么也没听到,并且更新(LineListener 的一部分)没有被调用,除了在开始时一次(开始)和最后几次(停止,关闭)。

这很奇怪,因为我在之前的项目中将 SourceDataLine 用作 8 位签名单声道 pcm,并且成功了。因此,我还尝试通过仅从短数组中获取每个其他高字节来将新版本测试为 8 位单声道。 SourceDataLine 只接受字节数组。
public class JavaxAudioDevice implements AudioInterface, LineListener {

    // omitted stuff

    short[] curBuf;
    byte[] byteBuf;

    SourceDataLine Output;
    int leader = 1024; //leader "tape"

    @Override
    public int create() {
        quit = false;
        AudioFormat af = new AudioFormat(44100, 16, 2, true, false);
//        AudioFormat af = new AudioFormat(44100, 8, 1, true, false);
        try {
            Output = AudioSystem.getSourceDataLine(af);
        } catch (Exception e) {
            System.err.println("Failed to create audio device. " + e.getLocalizedMessage());
            return 1;
        }

        if (Output != null) {
            try {
                Output.open(af,leader);
            } catch (Exception e) {
                System.err.println("Failed to open audio device. " + e.getLocalizedMessage());
                return 2;
            }
            Output.addLineListener(this);
        }
        System.err.println("Created JavaxAudioDevice");
        byte[] bytes = new byte[leader];
        alreadyLead = true;
        Output.write(bytes, 0, bytes.length);
        Output.start();
        System.err.println(Output.getFormat().toString());
        return 0;
    }

//omitted stuff

//LineListener
    @Override
    public void update(LineEvent le) {
            if (le == null) System.err.println("Audio update");
            else System.err.println("Audio update " + le.toString());

        if ( !quit && ( le == null || le.getType() == LineEvent.Type.STOP ) ) {
            boolean uf = false;
            while (notDoneYet) {
                uf = true;
            }

            notDoneYet = true;
            if (uf) {
                underflow = true;
                System.err.println("underflow");
            }

            if (byteBuf == null) { //insert some leader tape
                byteBuf = new byte[leader];
                for (int i = 0; i < byteBuf.length; ++i)
                    byteBuf[i] = 0;

                if (alreadyLead) System.err.println("Using audio leader when not supposed to!");
                else alreadyLead = true;
            }
            Output.write(byteBuf, 0, byteBuf.length);
            Output.start();
            byteBuf = null;
            if (!Output.isRunning()) { //debug
                System.err.println("Output not running");
            } else {
                System.err.println("Output running");
            }

            aplay.call();
            curBuf = aplay.output;
            if (curBuf == null) {
                //I don't know how to help you
                notDoneYet = false;
                System.err.println("Unable to fill buffer");
                return;
            }
            byteBuf = new byte[curBuf.length * 2];
            for (int i = 0; i < byteBuf.length; ++i) {
                //little endian
                if (i % 2 == 0) byteBuf[i] = (byte) (curBuf[i / 2]/*&255/**/); //low byte
                else byteBuf[i] = (byte) (curBuf[i / 2] >> 8); //high byte
            }

//            byteBuf = new byte[curBuf.length/2]; //debug 8 bit mono
//            for (int i = 0; i < byteBuf.length; ++i) {
//                byteBuf[i] = (byte) (curBuf[i*2] >> 8);
//            }

            notDoneYet = false;
        }

    }
}

一些示例输出:
Created JavaxAudioDevice
Audio update Start event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@13ab2987
PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian
Disposing
Audio update Stop event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@13ab2987
Audio update Close event from line com.sun.media.sound.DirectAudioDevice$DirectSDL@13ab2987
:desktop:run

BUILD SUCCESSFUL

Total time: 33.128 secs

“处置”及以下是我退出程序后。每秒应该有几次音频更新以重新填充缓冲区。

在这一点上,我不知道接下来要尝试什么。

最佳答案

好的,我想出了我的答案。我之前对 javax.sound.sampled 主线程的实验涉及生成缓冲区并在检测到声音完成时重新启动声音。在那个实验中,我在这里尝试做的是在 SDL 中使用 LineListener,比如 Mix_HookMusic()(一个更老的实验)。

https://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer.html#SEC60

当 SDL_mixer 用完缓冲区时,它会调用您提供的函数来制作更多。这不是 LineListener 在 java 中的工作方式。当缓冲区用完时不会调用它。

相反,把它当作它自己的线程(它是)。当您调用 SourceDataLine.start() 时,它会在其自己的线程中以 start 事件类型启动 LineListener 的事件函数并返回到主线程。因此,当 LineListener 检测到启动事件时,它会进入一个循环,该循环创建一个缓冲区并将其写入设备。 SourceDataLine.write() 当它有一个或更少的缓冲区要通过时返回。这给了循环足够的时间来制作另一个具有恰好一个缓冲区的延迟。 SourceDataLine.stop() 将启动另一个具有停止类型的 LineListener 事件函数。现在事件函数的第二个线程可以设置一个 boolean 值,这样第一个线程就知道是时候退出并退出循环了。

这是一些示例代码,它播放 5 秒钟的音,然后在退出前再静音 5 秒钟。

编辑:似乎至少写一帧(我称之为样本)对于确保 SourceDataLine.start() 能够正常工作很重要。由于我使用的是 16 位立体声,因此我需要 device.write(new byte[4],0,4);至少在我调用 device.start(); 之前

JavaxAudioTest.java

package javaxaudiotest;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class JavaxAudioTest {

    public static void main(String[] args) {
        SourceDataLine device;
        int buffer = 44100/15; //buffer in bytes (4 per sample so 60 buffers per second)

        AudioFormat af = new AudioFormat(44100, 16, 2, true, false);
        try {
            device = (SourceDataLine) AudioSystem.getSourceDataLine(af);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(JavaxAudioTest.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }


        WaveGen wg = new WaveGen();
        JavaxAudioDevice jad = new JavaxAudioDevice();
        jad.gen = wg;
        jad.device = device;
        device.addLineListener(jad);

        try {
            device.open(af,buffer);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(JavaxAudioTest.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
        device.write(new byte[4], 0, 4); //absolutely essential
        device.start();

        System.out.println("Zzzzzzzzzz");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaxAudioTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("zzzzzzzzzzBWAH!");
        device.close();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaxAudioTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Baiyo");
        device.drain();
        device.close();
    }
}

JavaxAudioDevice.java
package javaxaudiotest;

import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.SourceDataLine;

public class JavaxAudioDevice implements LineListener {
    boolean quit = false;
    byte[] byteBuf;
    int SampleRate = 44100;
    int buffer = SampleRate/60;
    public WaveGen gen;
    public SourceDataLine device;


    @Override
    public void update(LineEvent event) {
        System.out.println(event.toString());
        if (event.getType() == LineEvent.Type.STOP) {
            quit = true;
        }
        else if (event.getType() == LineEvent.Type.START) {
            while (!quit) {
                short[] buf = new short[buffer];
                for (int i=0; i<buf.length; ++i) {
                    buf[i] = gen.Output();
                }
                byteBuf = new byte[buf.length*4];
                for (int i=0; i<buf.length; ++i) {
                    byteBuf[i*4] = byteBuf[i*4+2] = (byte)buf[i];
                    byteBuf[i*4+1] = byteBuf[i*4+3] = (byte)(buf[i]>>8);
                }
                device.write(byteBuf, 0, byteBuf.length);
            }
        }
    }

}

WaveGen.java
package javaxaudiotest;

public class WaveGen {
    int Wave = 0;
    int Max = 1<<24;
    byte Fidelity = 20;
    int Level = 8;
    int Boost = 2000;
    int Stepper = (int)(110.0/44100*Max); //freq/44100*2^24

    short Output() {
        short ret = 0;
        Wave += Stepper;
        Wave %= Max;
        ret = (short)(( (Wave>>Fidelity)-Level )*Boost);
        return ret;
    }
}

关于Java SourceDataLine 未在第一个缓冲区结束时调用更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197292/

相关文章:

ios - 在 iOS 中播放和查找音频文件

java - Libgdx - 如何为每个部分的不同输入处理器拆分屏幕

java - LibGDX:如何在FitViewport的黑条区域中绘制?

java - 为什么 Guava 的 MultiMap 的 size 方法返回(非)预期的结果?

java - 在浏览器中对 pdf 进行数字签名

java - Spring - 在 Controller 中检查路径变量是否为空

java - LibGDX:仅在特定区域内显示 Sprite

java - 最长回文子序列算法,时间分析

java - 使用JLGui更改系统音量

macos - 具有自定义频率和持续时间的蜂鸣声