Path: blob/master/src/java.desktop/share/classes/javax/sound/sampled/DataLine.java
41159 views
/*1* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.sound.sampled;2627import java.util.Arrays;2829/**30* {@code DataLine} adds media-related functionality to its superinterface,31* {@code Line}. This functionality includes transport-control methods that32* start, stop, drain, and flush the audio data that passes through the line. A33* data line can also report the current position, volume, and audio format of34* the media. Data lines are used for output of audio by means of the35* subinterfaces {@link SourceDataLine} or {@link Clip}, which allow an36* application program to write data. Similarly, audio input is handled by the37* subinterface {@link TargetDataLine}, which allows data to be read.38* <p>39* A data line has an internal buffer in which the incoming or outgoing audio40* data is queued. The {@link #drain()} method blocks until this internal buffer41* becomes empty, usually because all queued data has been processed. The42* {@link #flush()} method discards any available queued data from the internal43* buffer.44* <p>45* A data line produces {@link LineEvent.Type#START START} and46* {@link LineEvent.Type#STOP STOP} events whenever it begins or ceases active47* presentation or capture of data. These events can be generated in response to48* specific requests, or as a result of less direct state changes. For example,49* if {@link #start()} is called on an inactive data line, and data is available50* for capture or playback, a {@code START} event will be generated shortly,51* when data playback or capture actually begins. Or, if the flow of data to an52* active data line is constricted so that a gap occurs in the presentation of53* data, a {@code STOP} event is generated.54* <p>55* Mixers often support synchronized control of multiple data lines.56* Synchronization can be established through the {@code Mixer} interface's57* {@link Mixer#synchronize synchronize} method. See the description of the58* {@link Mixer Mixer} interface for a more complete description.59*60* @author Kara Kytle61* @see LineEvent62* @since 1.363*/64public interface DataLine extends Line {6566/**67* Drains queued data from the line by continuing data I/O until the data68* line's internal buffer has been emptied. This method blocks until the69* draining is complete. Because this is a blocking method, it should be70* used with care. If {@code drain()} is invoked on a stopped line that has71* data in its queue, the method will block until the line is running and72* the data queue becomes empty. If {@code drain()} is invoked by one73* thread, and another continues to fill the data queue, the operation will74* not complete. This method always returns when the data line is closed.75*76* @see #flush()77*/78void drain();7980/**81* Flushes queued data from the line. The flushed data is discarded. In some82* cases, not all queued data can be discarded. For example, a mixer can83* flush data from the buffer for a specific input line, but any unplayed84* data already in the output buffer (the result of the mix) will still be85* played. You can invoke this method after pausing a line (the normal case)86* if you want to skip the "stale" data when you restart playback or87* capture. (It is legal to flush a line that is not stopped, but doing so88* on an active line is likely to cause a discontinuity in the data,89* resulting in a perceptible click.)90*91* @see #stop()92* @see #drain()93*/94void flush();9596/**97* Allows a line to engage in data I/O. If invoked on a line that is already98* running, this method does nothing. Unless the data in the buffer has been99* flushed, the line resumes I/O starting with the first frame that was100* unprocessed at the time the line was stopped. When audio capture or101* playback starts, a {@link LineEvent.Type#START START} event is generated.102*103* @see #stop()104* @see #isRunning()105* @see LineEvent106*/107void start();108109/**110* Stops the line. A stopped line should cease I/O activity. If the line is111* open and running, however, it should retain the resources required to112* resume activity. A stopped line should retain any audio data in its113* buffer instead of discarding it, so that upon resumption the I/O can114* continue where it left off, if possible. (This doesn't guarantee that115* there will never be discontinuities beyond the current buffer, of course;116* if the stopped condition continues for too long, input or output samples117* might be dropped.) If desired, the retained data can be discarded by118* invoking the {@code flush} method. When audio capture or playback stops,119* a {@link LineEvent.Type#STOP STOP} event is generated.120*121* @see #start()122* @see #isRunning()123* @see #flush()124* @see LineEvent125*/126void stop();127128/**129* Indicates whether the line is running. The default is {@code false}. An130* open line begins running when the first data is presented in response to131* an invocation of the {@code start} method, and continues until132* presentation ceases in response to a call to {@code stop} or because133* playback completes.134*135* @return {@code true} if the line is running, otherwise {@code false}136* @see #start()137* @see #stop()138*/139boolean isRunning();140141/**142* Indicates whether the line is engaging in active I/O (such as playback or143* capture). When an inactive line becomes active, it sends a144* {@link LineEvent.Type#START START} event to its listeners. Similarly,145* when an active line becomes inactive, it sends a146* {@link LineEvent.Type#STOP STOP} event.147*148* @return {@code true} if the line is actively capturing or rendering149* sound, otherwise {@code false}150* @see #isOpen151* @see #addLineListener152* @see #removeLineListener153* @see LineEvent154* @see LineListener155*/156boolean isActive();157158/**159* Obtains the current format (encoding, sample rate, number of channels,160* etc.) of the data line's audio data.161* <p>162* If the line is not open and has never been opened, it returns the default163* format. The default format is an implementation specific audio format,164* or, if the {@code DataLine.Info} object, which was used to retrieve this165* {@code DataLine}, specifies at least one fully qualified audio format,166* the last one will be used as the default format. Opening the line with a167* specific audio format (e.g. {@link SourceDataLine#open(AudioFormat)})168* will override the default format.169*170* @return current audio data format171* @see AudioFormat172*/173AudioFormat getFormat();174175/**176* Obtains the maximum number of bytes of data that will fit in the data177* line's internal buffer. For a source data line, this is the size of the178* buffer to which data can be written. For a target data line, it is the179* size of the buffer from which data can be read. Note that the units used180* are bytes, but will always correspond to an integral number of sample181* frames of audio data.182*183* @return the size of the buffer, in bytes184*/185int getBufferSize();186187/**188* Obtains the number of bytes of data currently available to the189* application for processing in the data line's internal buffer. For a190* source data line, this is the amount of data that can be written to the191* buffer without blocking. For a target data line, this is the amount of192* data available to be read by the application. For a clip, this value is193* always 0 because the audio data is loaded into the buffer when the clip194* is opened, and persists without modification until the clip is closed.195* <p>196* Note that the units used are bytes, but will always correspond to an197* integral number of sample frames of audio data.198* <p>199* An application is guaranteed that a read or write operation of up to the200* number of bytes returned from {@code available()} will not block;201* however, there is no guarantee that attempts to read or write more data202* will block.203*204* @return the amount of data available, in bytes205*/206int available();207208/**209* Obtains the current position in the audio data, in sample frames. The210* frame position measures the number of sample frames captured by, or211* rendered from, the line since it was opened. This return value will wrap212* around after 2^31 frames. It is recommended to use213* {@code getLongFramePosition} instead.214*215* @return the number of frames already processed since the line was opened216* @see #getLongFramePosition()217*/218int getFramePosition();219220/**221* Obtains the current position in the audio data, in sample frames. The222* frame position measures the number of sample frames captured by, or223* rendered from, the line since it was opened.224*225* @return the number of frames already processed since the line was opened226* @since 1.5227*/228long getLongFramePosition();229230/**231* Obtains the current position in the audio data, in microseconds. The232* microsecond position measures the time corresponding to the number of233* sample frames captured by, or rendered from, the line since it was234* opened. The level of precision is not guaranteed. For example, an235* implementation might calculate the microsecond position from the current236* frame position and the audio sample frame rate. The precision in237* microseconds would then be limited to the number of microseconds per238* sample frame.239*240* @return the number of microseconds of data processed since the line was241* opened242*/243long getMicrosecondPosition();244245/**246* Obtains the current volume level for the line. This level is a measure of247* the signal's current amplitude, and should not be confused with the248* current setting of a gain control. The range is from 0.0 (silence) to 1.0249* (maximum possible amplitude for the sound waveform). The units measure250* linear amplitude, not decibels.251*252* @return the current amplitude of the signal in this line, or253* {@link AudioSystem#NOT_SPECIFIED}254*/255float getLevel();256257/**258* Besides the class information inherited from its superclass,259* {@code DataLine.Info} provides additional information specific to data260* lines. This information includes:261* <ul>262* <li>the audio formats supported by the data line263* <li>the minimum and maximum sizes of its internal buffer264* </ul>265* Because a {@code Line.Info} knows the class of the line its describes, a266* {@code DataLine.Info} object can describe {@code DataLine} subinterfaces267* such as {@link SourceDataLine}, {@link TargetDataLine}, and {@link Clip}.268* You can query a mixer for lines of any of these types, passing an269* appropriate instance of {@code DataLine.Info} as the argument to a method270* such as {@link Mixer#getLine(Line.Info)}.271*272* @author Kara Kytle273* @see Line.Info274* @since 1.3275*/276class Info extends Line.Info {277278/**279* The set of supported formats.280*/281private final AudioFormat[] formats;282283/**284* Minimum buffer size supported by the data line, in bytes.285*/286private final int minBufferSize;287288/**289* Maximum buffer size supported by the data line, in bytes.290*/291private final int maxBufferSize;292293/**294* Constructs a data line's info object from the specified information,295* which includes a set of supported audio formats and a range for the296* buffer size. This constructor is typically used by mixer297* implementations when returning information about a supported line.298*299* @param lineClass the class of the data line described by the info300* object301* @param formats set of formats supported302* @param minBufferSize minimum buffer size supported by the data line,303* in bytes304* @param maxBufferSize maximum buffer size supported by the data line,305* in bytes306*/307public Info(Class<?> lineClass, AudioFormat[] formats, int minBufferSize, int maxBufferSize) {308309super(lineClass);310311if (formats == null) {312this.formats = new AudioFormat[0];313} else {314this.formats = Arrays.copyOf(formats, formats.length);315}316317this.minBufferSize = minBufferSize;318this.maxBufferSize = maxBufferSize;319}320321/**322* Constructs a data line's info object from the specified information,323* which includes a single audio format and a desired buffer size. This324* constructor is typically used by an application to describe a desired325* line.326*327* @param lineClass the class of the data line described by the info328* object329* @param format desired format330* @param bufferSize desired buffer size, in bytes331*/332public Info(Class<?> lineClass, AudioFormat format, int bufferSize) {333334super(lineClass);335336if (format == null) {337this.formats = new AudioFormat[0];338} else {339this.formats = new AudioFormat[]{format};340}341342this.minBufferSize = bufferSize;343this.maxBufferSize = bufferSize;344}345346/**347* Constructs a data line's info object from the specified information,348* which includes a single audio format. This constructor is typically349* used by an application to describe a desired line.350*351* @param lineClass the class of the data line described by the info352* object353* @param format desired format354*/355public Info(Class<?> lineClass, AudioFormat format) {356this(lineClass, format, AudioSystem.NOT_SPECIFIED);357}358359/**360* Obtains a set of audio formats supported by the data line. Note that361* {@code isFormatSupported(AudioFormat)} might return {@code true} for362* certain additional formats that are missing from the set returned by363* {@code getFormats()}. The reverse is not the case:364* {@code isFormatSupported(AudioFormat)} is guaranteed to return365* {@code true} for all formats returned by {@code getFormats()}.366* <p>367* Some fields in the {@code AudioFormat} instances can be set to368* {@link AudioSystem#NOT_SPECIFIED NOT_SPECIFIED} if that field does369* not apply to the format, or if the format supports a wide range of370* values for that field. For example, a multi-channel device supporting371* up to 64 channels, could set the channel field in the372* {@code AudioFormat} instances returned by this method to373* {@code NOT_SPECIFIED}.374*375* @return a set of supported audio formats376* @see #isFormatSupported(AudioFormat)377*/378public AudioFormat[] getFormats() {379return Arrays.copyOf(formats, formats.length);380}381382/**383* Indicates whether this data line supports a particular audio format.384* The default implementation of this method simply returns {@code true}385* if the specified format matches any of the supported formats.386*387* @param format the audio format for which support is queried388* @return {@code true} if the format is supported, otherwise389* {@code false}390* @see #getFormats391* @see AudioFormat#matches392*/393public boolean isFormatSupported(AudioFormat format) {394395for (int i = 0; i < formats.length; i++) {396if (format.matches(formats[i])) {397return true;398}399}400401return false;402}403404/**405* Obtains the minimum buffer size supported by the data line.406*407* @return minimum buffer size in bytes, or408* {@code AudioSystem.NOT_SPECIFIED}409*/410public int getMinBufferSize() {411return minBufferSize;412}413414/**415* Obtains the maximum buffer size supported by the data line.416*417* @return maximum buffer size in bytes, or418* {@code AudioSystem.NOT_SPECIFIED}419*/420public int getMaxBufferSize() {421return maxBufferSize;422}423424/**425* Determines whether the specified info object matches this one. To426* match, the superclass match requirements must be met. In addition,427* this object's minimum buffer size must be at least as large as that428* of the object specified, its maximum buffer size must be at most as429* large as that of the object specified, and all of its formats must430* match formats supported by the object specified.431*432* @param info the info object which is being compared to this one433* @return {@code true} if this object matches the one specified,434* otherwise {@code false}435*/436@Override437public boolean matches(Line.Info info) {438439if (! (super.matches(info)) ) {440return false;441}442443Info dataLineInfo = (Info)info;444445// treat anything < 0 as NOT_SPECIFIED446// demo code in old Java Sound Demo used a wrong buffer calculation447// that would lead to arbitrary negative values448if ((getMaxBufferSize() >= 0) && (dataLineInfo.getMaxBufferSize() >= 0)) {449if (getMaxBufferSize() > dataLineInfo.getMaxBufferSize()) {450return false;451}452}453454if ((getMinBufferSize() >= 0) && (dataLineInfo.getMinBufferSize() >= 0)) {455if (getMinBufferSize() < dataLineInfo.getMinBufferSize()) {456return false;457}458}459460AudioFormat[] localFormats = getFormats();461462if (localFormats != null) {463464for (int i = 0; i < localFormats.length; i++) {465if (! (localFormats[i] == null) ) {466if (! (dataLineInfo.isFormatSupported(localFormats[i])) ) {467return false;468}469}470}471}472473return true;474}475476/**477* Returns a string representation of the info object.478*479* @return a string representation of the info object480*/481@Override482public String toString() {483String format = "";484AudioFormat[] formats = getFormats();485if (formats.length == 1 && formats[0] != null) {486format = " supporting format " + formats[0];487} else if (formats.length > 1) {488format = " supporting " + formats.length + " audio formats";489}490491String buffers = "";492int min = getMinBufferSize();493int max = getMaxBufferSize();494if (min != AudioSystem.NOT_SPECIFIED495&& max != AudioSystem.NOT_SPECIFIED) {496buffers = ", and buffers of " + min + " to " + max + " bytes";497} else if (min > 0) {498buffers = ", and buffers of at least " + min + " bytes";499} else if (max != AudioSystem.NOT_SPECIFIED) {500buffers = ", and buffers of up to " + max + " bytes";501}502503return String.format("%s%s%s", super.toString(), format, buffers);504}505}506}507508509