下面列出了怎么用javax.sound.sampled.SourceDataLine的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean createSourceDataLine() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
// fail silently
return false;
}
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (datapusher==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
return true;
}
public void run() {
byte[] buffer = SoftAudioPusher.this.buffer;
AudioInputStream ais = SoftAudioPusher.this.ais;
SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine;
try {
while (active) {
// Read from audio source
int count = ais.read(buffer);
if(count < 0) break;
// Write byte buffer to source output
sourceDataLine.write(buffer, 0, count);
}
} catch (IOException e) {
active = false;
//e.printStackTrace();
}
}
/** Obtain the value of a default provider property.
@param typeClass The type of the default provider property. This
should be one of Receiver.class, Transmitter.class, Sequencer.class,
Synthesizer.class, SourceDataLine.class, TargetDataLine.class,
Clip.class or Port.class.
@return The complete value of the property, if available.
If the property is not set, null is returned.
*/
private static synchronized String getDefaultProvider(Class typeClass) {
if (!SourceDataLine.class.equals(typeClass)
&& !TargetDataLine.class.equals(typeClass)
&& !Clip.class.equals(typeClass)
&& !Port.class.equals(typeClass)
&& !Receiver.class.equals(typeClass)
&& !Transmitter.class.equals(typeClass)
&& !Synthesizer.class.equals(typeClass)
&& !Sequencer.class.equals(typeClass)) {
return null;
}
String name = typeClass.getName();
String value = AccessController.doPrivileged(
(PrivilegedAction<String>) () -> System.getProperty(name));
if (value == null) {
value = getProperties().getProperty(name);
}
if ("".equals(value)) {
value = null;
}
return value;
}
public void run() {
byte[] buffer = SoftAudioPusher.this.buffer;
AudioInputStream ais = SoftAudioPusher.this.ais;
SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine;
try {
while (active) {
// Read from audio source
int count = ais.read(buffer);
if(count < 0) break;
// Write byte buffer to source output
sourceDataLine.write(buffer, 0, count);
}
} catch (IOException e) {
active = false;
//e.printStackTrace();
}
}
private boolean createSourceDataLine() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
// fail silently
return false;
}
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (datapusher==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
return true;
}
private boolean createSourceDataLine() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
// fail silently
return false;
}
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (datapusher==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
return true;
}
public boolean play(SWFInputStream sis) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!decode(sis, baos)) {
return false;
}
AudioFormat audioFormat = new AudioFormat(samplingRate, 16, stereo ? 2 : 1, true, false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
line.open(audioFormat);
byte[] outData = baos.toByteArray();
line.write(outData, 0, outData.length);
line.drain();
line.stop();
return true;
} catch (LineUnavailableException ex) {
return false;
}
}
public static void rawplay(AudioFormat targetFormat, AudioInputStream din)
throws IOException, LineUnavailableException {
byte[] data = new byte[CommonValues.IOBufferLength];
DataLine.Info info = new DataLine.Info(SourceDataLine.class, targetFormat);
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(targetFormat);
if (line != null) {
// Start
FloatControl vol = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
logger.debug(vol.getValue() + vol.getUnits());
line.start();
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1) {
nBytesWritten = line.write(data, 0, nBytesRead);
}
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
}
}
private boolean createSourceDataLine() {
if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
if (!(AudioSystem.isLineSupported(info)) ) {
if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
// fail silently
return false;
}
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
} catch (Exception e) {
if (DEBUG || Printer.err)e.printStackTrace();
// fail silently
return false;
}
if (datapusher==null) {
// fail silently
return false;
}
if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
return true;
}
public void run() {
byte[] buffer = SoftAudioPusher.this.buffer;
AudioInputStream ais = SoftAudioPusher.this.ais;
SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine;
try {
while (active) {
// Read from audio source
int count = ais.read(buffer);
if(count < 0) break;
// Write byte buffer to source output
sourceDataLine.write(buffer, 0, count);
}
} catch (IOException e) {
active = false;
//e.printStackTrace();
}
}
public static void tone(int hz, int msecs, double vol) throws LineUnavailableException {
byte[] buf = new byte[1];
AudioFormat af = new AudioFormat(SAMPLE_RATE, // sampleRate
8, // sampleSizeInBits
1, // channels
true, // signed
false); // bigEndian
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
for (int i = 0; i < msecs * 8; i++) {
double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
buf[0] = (byte) (Math.sin(angle) * 127.0 * vol);
sdl.write(buf, 0, 1);
}
sdl.drain();
sdl.stop();
sdl.close();
}
/** Close all audio lines. */
public void close() {
if (exec != null) {
exec.shutdown();
for (SourceDataLine sdl : lines) {
sdl.close();
}
try {
exec.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
// ignored
}
exec.shutdownNow();
lines.clear();
soundPool.clear();
soundMap.clear();
soundFormat.clear();
exec = null;
}
}
/** Obtain the value of a default provider property.
@param typeClass The type of the default provider property. This
should be one of Receiver.class, Transmitter.class, Sequencer.class,
Synthesizer.class, SourceDataLine.class, TargetDataLine.class,
Clip.class or Port.class.
@return The complete value of the property, if available.
If the property is not set, null is returned.
*/
private static synchronized String getDefaultProvider(Class<?> typeClass) {
if (!SourceDataLine.class.equals(typeClass)
&& !TargetDataLine.class.equals(typeClass)
&& !Clip.class.equals(typeClass)
&& !Port.class.equals(typeClass)
&& !Receiver.class.equals(typeClass)
&& !Transmitter.class.equals(typeClass)
&& !Synthesizer.class.equals(typeClass)
&& !Sequencer.class.equals(typeClass)) {
return null;
}
String name = typeClass.getName();
String value = AccessController.doPrivileged(
(PrivilegedAction<String>) () -> System.getProperty(name));
if (value == null) {
value = getProperties().getProperty(name);
}
if ("".equals(value)) {
value = null;
}
return value;
}
public int getMaxLines(Line.Info info) {
if (info.getLineClass() == SourceDataLine.class)
return AudioSystem.NOT_SPECIFIED;
if (info.getLineClass() == Clip.class)
return AudioSystem.NOT_SPECIFIED;
return 0;
}
private SourceDataLine getOutputLine(int channels, int rate) {
if (outputLine == null || this.rate != rate || this.channels != channels) {
if (outputLine != null) {
outputLine.drain();
outputLine.stop();
outputLine.close();
}
initJavaSound(channels, rate);
outputLine.start();
}
return outputLine;
}
private void init(SourceDataLine line, AudioFormat audioFormat, Time bufferDuration)
{
mBufferDuration.set(bufferDuration);
mAudioFormat = audioFormat;
if(line != null)
{
logger.info("opening sound system with line \"" + line + "\" and audio format \"" + audioFormat + "\"");
mSystemOutput = new SystemOutput(line);
}
else
{
mSystemOutput = null;
}
}
PlayAudioThread(AudioInputStream stream, StartTime startTime,
SourceDataLine dataLine, Listener listener,
Cancellable cancellable) {
super("Play Audio " + (threadNameCtr++));
if (stream == null)
throw new NullPointerException();
if (dataLine == null)
throw new NullPointerException();
this.stream = stream;
this.dataLine = dataLine;
this.startTime = startTime;
this.listener = listener == null ? new NullListener() : listener;
this.cancellable = cancellable == null ? new BasicCancellable()
: cancellable;
}
public Line getLine(Line.Info info) throws LineUnavailableException {
if (!isLineSupported(info))
throw new IllegalArgumentException("Line unsupported: " + info);
if ((info.getLineClass() == SourceDataLine.class)) {
return new SoftMixingSourceDataLine(this, (DataLine.Info) info);
}
if ((info.getLineClass() == Clip.class)) {
return new SoftMixingClip(this, (DataLine.Info) info);
}
throw new IllegalArgumentException("Line unsupported: " + info);
}
public Line getLine(Line.Info info) throws LineUnavailableException {
if (!isLineSupported(info))
throw new IllegalArgumentException("Line unsupported: " + info);
if ((info.getLineClass() == SourceDataLine.class)) {
return new SoftMixingSourceDataLine(this, (DataLine.Info) info);
}
if ((info.getLineClass() == Clip.class)) {
return new SoftMixingClip(this, (DataLine.Info) info);
}
throw new IllegalArgumentException("Line unsupported: " + info);
}
public int getMaxLines(Line.Info info) {
if (info.getLineClass() == SourceDataLine.class)
return AudioSystem.NOT_SPECIFIED;
if (info.getLineClass() == Clip.class)
return AudioSystem.NOT_SPECIFIED;
return 0;
}
private static void sortDeviceList(List<Device> devices, AudioFormat audioFormat)
{
final DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
Collections.sort(devices, new Comparator<Device>()
{
@Override
public int compare(Device device1, Device device2)
{
int numLines1 = device1.mMixer.getMaxLines(dataLineInfo);
int numLines2 = device2.mMixer.getMaxLines(dataLineInfo);
if(numLines2 == 0) {
return -1;
}
if(device1.mRating == device2.mRating)
{
if(numLines1 == AudioSystem.NOT_SPECIFIED || numLines1 > numLines2) {
return -1;
}
}
else
{
if(device1.mRating > device2.mRating) {
return -1;
}
}
return 1;
}
});
}
public void Play(byte[] secbytesarray, AudioFormat af, SourceDataLine line1, int sp, byte[] data) throws LineUnavailableException{
for(int i=0;i<sp;i++){
for(int j=0;j<data.length;j++){
data[j]=secbytesarray[j+i*data.length];
}
line1.write(data, 0, data.length);
}
}
public int getMaxLines(Line.Info info) {
if (info.getLineClass() == SourceDataLine.class)
return AudioSystem.NOT_SPECIFIED;
if (info.getLineClass() == Clip.class)
return AudioSystem.NOT_SPECIFIED;
return 0;
}
public int getMaxLines(Line.Info info) {
if (info.getLineClass() == SourceDataLine.class)
return AudioSystem.NOT_SPECIFIED;
if (info.getLineClass() == Clip.class)
return AudioSystem.NOT_SPECIFIED;
return 0;
}
public void returnLine(Object requester) {
if (activeLines.containsKey(requester)) {
SourceDataLine sdl = activeLines.remove(requester);
// Calling drain on pulse driver can cause it to freeze up (?)
// sdl.drain();
if (sdl.isRunning()) {
sdl.flush();
sdl.stop();
}
availableLines.add(sdl);
}
}
public int getMaxLines(Line.Info info) {
if (info.getLineClass() == SourceDataLine.class)
return AudioSystem.NOT_SPECIFIED;
if (info.getLineClass() == Clip.class)
return AudioSystem.NOT_SPECIFIED;
return 0;
}
private static boolean doMixerSDL(Mixer mixer, AudioFormat format) {
if (mixer==null) return false;
try {
System.out.println("Trying mixer "+mixer+":");
DataLine.Info info = new DataLine.Info(
SourceDataLine.class,
format,
(int) samplerate);
SourceDataLine sdl = (SourceDataLine) mixer.getLine(info);
System.out.println(" - got sdl: "+sdl);
System.out.println(" - open with format "+format);
sdl.open(format);
System.out.println(" - start...");
sdl.start();
System.out.println(" - write...");
sdl.write(buffer, 0, buffer.length);
Thread.sleep(200);
System.out.println(" - drain...");
sdl.drain();
System.out.println(" - stop...");
sdl.stop();
System.out.println(" - close...");
sdl.close();
System.out.println(" - closed");
} catch (Throwable t) {
System.out.println(" - Caught exception. Not failed.");
System.out.println(" - "+t.toString());
return false;
}
return true;
}
public void proceed(Time delay, SourceDataLine outputLine)
{
if(outputLine != null && !outputLine.getFormat().matches(mAudioFormat)) {
throw new IllegalArgumentException("outputLine has the wrong audio format");
}
init(outputLine, mAudioFormat, mBufferDuration.get());
changeSystemState(STATE_RUNNING, delay);
}
public Line getLine(Line.Info info) throws LineUnavailableException {
if (!isLineSupported(info))
throw new IllegalArgumentException("Line unsupported: " + info);
if ((info.getLineClass() == SourceDataLine.class)) {
return new SoftMixingSourceDataLine(this, (DataLine.Info) info);
}
if ((info.getLineClass() == Clip.class)) {
return new SoftMixingClip(this, (DataLine.Info) info);
}
throw new IllegalArgumentException("Line unsupported: " + info);
}
/**
* Initialize all channels.
* @param channels the number of parallel effects
* @param getVolume the function which returns the current volume,
* asked once before an effect plays. Volume of 0 means no sound
*/
public void initialize(int channels, final Func0<Integer> getVolume) {
this.getVolume = getVolume;
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
channels, channels, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(channels),
new ThreadFactory() {
/** The thread numbering. */
final AtomicInteger tid = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "UISounds-" + tid.incrementAndGet());
}
}
/*
,
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.err.println("Rejected");
}
}
*/
);
exec = tpe;
effectSemaphore = new Semaphore(channels);
// initialize the sound pool
for (AudioFormatType aft : soundFormat.values()) {
if (!soundPool.containsKey(aft)) {
soundPool.put(aft, new LinkedBlockingQueue<SourceDataLine>());
}
}
}