java - 打开 TargetDataLine 时未引发异常

标签 java audio javasound

根据Javadocs,当我使用javax.sound.sampledTargetDataLine的以下方法时:

public void open(AudioFormat format,int bufferSize)

其中说:

Invoking this method with a requested buffer size that does not meet this requirement may result in an IllegalArgumentException.`

所以当我实现以下Java代码时:

AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);

// open the TargetDataLine for capture.
try {
     TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
     line.open(format, line.getBufferSize()+3000); 
    }    
catch (LineUnavailableException ex)
{         
   ex.printStackTrace();        
}

但是当我运行上面的代码时它不会抛出任何异常。现在根据文档:

public int getBufferSize()
Obtains the maximum number of bytes of data that will fit in the data line's internal buffer. For a source data line, this is the size of the buffer to which data can be written. For a target data line, it is the size of the buffer from which data can be read. Note that the units used are bytes, but will always correspond to an integral number of sample frames of audio data.

这表示将返回最大尺寸,并且我添加了 3000

line.open(format, line.getBufferSize()+3000); 

如上所示,为什么它没有抛出任何异常?

最佳答案

您遗漏了 JavaDoc 中有关 open 的一些重要描述。更完整地说,它说:

void open(AudioFormat format,
          int bufferSize)
          throws LineUnavailableException

Opens the line with the specified format and requested buffer size, causing the line to acquire any required system resources and become operational. The buffer size is specified in bytes, but must represent an integral number of sample frames. Invoking this method with a requested buffer size that does not meet this requirement may result in an IllegalArgumentException. The actual buffer size for the open line may differ from the requested buffer size. The value actually set may be queried by subsequently calling DataLine.getBufferSize()

因此,您指定的缓冲区大小可能不是内部缓冲区的大小,甚至可能超过它。

但是,它必须“表示整数个样本帧”,否则将抛出 IllegalArgumentException。如果您请求的内存多于内部分配的内存,那么您将收到LineUnavailableException。这并不意味着请求比当前内部缓冲区更大的大小将导致 LineUnavailableException

至少这是我对文档的阅读。

关于java - 打开 TargetDataLine 时未引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633425/

相关文章:

javascript - 如何使用 JavaScript 媒体元素创建多个自定义 HTML5 音频播放器实例?

java - 在 Java 中播放 wav 时遇到问题

java - 顺畅的声音搜寻

Java 在 64 位 JVM 上的长性能

ios - 无法在 iOS 应用程序中播放简单的音效

android - 使用Android MediaPlayer流式传输ac3时无音频

java - Java游戏音效无法正常工作

java - 如何在Broadleaf中实现自己的ProductImpl?

java - 从另一个类访问最终变量并正确输出结果

java - 如何在 Spark 中实现自定义作业监听器/跟踪器?