クラスの定義ができあがりましたのでメインの処理を書きます。
メイン処理
まず今回定義したクラスのインスタンスを作ります。
final RecordTest recorder = new RecordTest(new File("midi/RecordAudio.wav"));
このクラスにスレッド定義つまりrunメソッドが書かれているのでこれをスレッドにします。
Thread stopper = new Thread(recorder);
ユーザーからプロンプトで入力させるためのReaderを作ります。これで録音開始と終了をユーザーにコントロールさせます。
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ユーザがエンターキーを押すのを待ちます。
System.out.print("enter to start recording >>");
in.readLine();
録音を開始します。
System.out.println("recording...");
stopper.start();
この処理は別スレッドで行われるためすぐに戻ってきます。スレッドの方では録音を開始していますのでユーザーの終了の合図を待ちます。
System.out.print("enter to stop recording >>");
in.readLine();
ユーザーの入力が来たら録音を終了させます。
recorder.stopRecording();
System.out.println("finished");
これで出力ファイルができているはずです。
実行結果
入出力の様子です。
enter to start recording >> recording... enter to stop recording >>starting line stopped stoped line closed finished
ソース
最後にソースを載せておきます。設定を変えるなどして色々試してみてください。今回は外部の音源の録音でしたが次回からは内部の音を拾うようにします。
import javax.sound.sampled.*;
import java.io.*;
public class RecordTest implements Runnable {
static final long RECORD_TIME = 100; // 0.1 sec
File wavFile;
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
static final float SAMPLE_RATE = 44100;
static final int SAMPLE_SIZE_IN_BITS = 16;
static final int CHANNELS = 2;
static final boolean SIGNED = true;
static final boolean BIG_ENDIAN = true;
TargetDataLine line;
RecordTest(File file) throws Exception {
AudioFormat format = new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE_IN_BITS, CHANNELS, SIGNED, BIG_ENDIAN);
wavFile = file;
line = AudioSystem.getTargetDataLine(format);
line.open(format);
}
void startRecording() {
try {
line.start();
AudioInputStream ais = new AudioInputStream(line);
AudioSystem.write(ais, fileType, wavFile);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
void stopRecording() {
line.stop();
line.close();
}
public static void main(String[] args) throws Exception {
final RecordTest recorder = new RecordTest(new File("midi/RecordAudio.wav"));
Thread stopper = new Thread(recorder);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter to start recording >>");
in.readLine();
System.out.println("recording...");
stopper.start();
System.out.print("enter to stop recording >>");
in.readLine();
recorder.stopRecording();
System.out.println("finished");
}
@Override
public void run() {
startRecording();
}
}