簡體   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