com.github.bloodshura.x.assets.device.CaptureThread Maven / Gradle / Ivy
/*
* Copyright (c) 2013-2018, João Vitor Verona Biazibetti - All Rights Reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*
* https://www.github.com/BloodShura
*/
package com.github.bloodshura.x.assets.device;
import com.github.bloodshura.x.assets.sound.SoundFormat;
import com.github.bloodshura.x.io.exception.FileException;
import com.github.bloodshura.x.io.file.TempFile;
import com.github.bloodshura.x.runnable.XThread;
import javax.annotation.Nonnull;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
class CaptureThread extends XThread {
public final AudioFormat audioFormat;
public final TargetDataLine currentLine;
public Object result;
public final SoundFormat soundFormat;
public CaptureThread(@Nonnull AudioFormat audioFormat, @Nonnull SoundFormat soundFormat) throws CaptureException {
super("Microphone Capture Thread");
try {
this.audioFormat = audioFormat;
this.currentLine = AudioSystem.getTargetDataLine(audioFormat);
this.result = null;
this.soundFormat = soundFormat;
}
catch (FileException | IllegalArgumentException | LineUnavailableException exception) {
throw new CaptureException("Could not create capture thread", exception);
}
}
public void close() {
currentLine.stop();
currentLine.close();
}
@Override
public void run() {
TempFile file = null;
try {
currentLine.open();
currentLine.start();
AudioFileFormat.Type handle = new AudioFileFormat.Type(soundFormat.getName(), soundFormat.getFormat());
file = new TempFile();
AudioSystem.write(new AudioInputStream(currentLine), handle, file.handle());
this.result = file.readData();
}
catch (Exception exception) {
this.result = exception;
}
finally {
if (file != null) {
file.delete();
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy