繁体   English   中英

Java长度无限的AudioInputStream

[英]Java Length Unlimited AudioInputStream

我有一堆代码,在运行时会产生过程声音。 不幸的是,它只持续几秒钟。 理想情况下,它将一直运行直到我告诉它停止为止。 我不是在谈论循环,生成它的算法目前提供2 ^ 64个样本,因此在可预见的将来它不会用完。 AudioInputStream的构造函数接受第三个输入,理想情况下,我可以将其删除。 我只能提供大量的信息,但这似乎是错误的解决方法。

我考虑过使用SourceDataLine,但理想情况下该算法将称为按需算法,而不是先行编写路径。 有什么想法吗?

看来我已经回答了我自己的问题。

经过进一步的研究,使用SourceDataLineSourceDataLine的方法,因为如果您给予足够的使用,它将阻塞。

抱歉,缺少适当的Javadoc。

class SoundPlayer
{
    // plays an InputStream for a given number of samples, length
    public static void play(InputStream stream, float sampleRate, int sampleSize, int length) throws LineUnavailableException
    {
        // you can specify whatever format you want...I just don't need much flexibility here
        AudioFormat format = new AudioFormat(sampleRate, sampleSize, 1, false, true);
        AudioInputStream audioStream = new AudioInputStream(stream, format, length);
        Clip clip = AudioSystem.getClip();
        clip.open(audioStream);
        clip.start();
    }

    public static void play(InputStream stream, float sampleRate, int sampleSize) throws LineUnavailableException
    {
        AudioFormat format = new AudioFormat(sampleRate, sampleSize, 1, false, true);
        SourceDataLine line = AudioSystem.getSourceDataLine(format);
        line.open(format);
        line.start();
        // if you wanted to block, you could just run the loop in here
        SoundThread soundThread = new SoundThread(stream, line);
        soundThread.start();
    }

    private static class SoundThread extends Thread
    {
        private static final int buffersize = 1024;

        private InputStream stream;
        private SourceDataLine line;

        SoundThread(InputStream stream, SourceDataLine line)
        {
            this.stream = stream;
            this.line = line;
        }

        public void run()
        {
            byte[] b = new byte[buffersize];
            // you could, of course, have a way of stopping this...
            for (;;)
            {
                stream.read(b);
                line.write(b, 0, buffersize);
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM