This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/client/data/AudioRecorder.java

69 lines
1.6 KiB
Java
Raw Normal View History

2020-07-03 14:17:04 +02:00
package envoy.client.data;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.sound.sampled.*;
import envoy.exception.EnvoyException;
/**
* Records audio and exports it as a byte array.
* <p>
* Project: <strong>envoy-client</strong><br>
* File: <strong>AudioRecorder.java</strong><br>
* Created: <strong>02.07.2020</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta
*/
public final class AudioRecorder {
private final AudioFormat format;
private DataLine.Info info;
private TargetDataLine line;
private Path tempFile;
public AudioRecorder() { this(new AudioFormat(16000, 16, 1, true, false)); }
public AudioRecorder(AudioFormat format) {
this.format = format;
info = new DataLine.Info(TargetDataLine.class, format);
}
public boolean isSupported() { return AudioSystem.isLineSupported(info); }
public void start() throws EnvoyException {
try {
// Open the line
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
// Prepare temp file
tempFile = Files.createTempFile("recording", "wav");
// Start the recording
var ais = new AudioInputStream(line);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, tempFile.toFile());
} catch (IOException | LineUnavailableException e) {
throw new EnvoyException("Cannot record voice", e);
}
}
public byte[] finish() throws EnvoyException {
try {
line.stop();
line.close();
byte[] data = Files.readAllBytes(tempFile);
Files.delete(tempFile);
return data;
} catch (IOException e) {
throw new EnvoyException("Cannot save voice recording", e);
}
}
}