【问题标题】:Java Length Unlimited AudioInputStreamJava 长度无限的 AudioInputStream
【发布时间】:2012-01-25 01:16:57
【问题描述】:

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

我考虑过使用 SourceDataLine,但理想情况下,该算法将按需调用,而不是提前运行并编写路径。想法?

【问题讨论】:

    标签: java audio stream javasound


    【解决方案1】:

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

    经过进一步研究,使用SourceDataLine 是可行的方法,因为当你给它足够的工作量时它会阻塞。

    对缺少适当的 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);
                }
            }
        }
    }
    

    【讨论】:

    • 我想我会在两天内接受这个答案......除非其他人提出更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多