Files
java-examples/docs/javax.sound.sampled.md

175 lines
6.1 KiB
Markdown

# **Java `javax.sound.sampled` 쉽게 배우기**
## **1. `javax.sound.sampled`란?**
`javax.sound.sampled` 패키지는 **자바에서 오디오(소리)를 다루는 기능**을 제공한다.
이를 이용하면 **오디오 파일을 재생, 녹음, 변환, 편집**할 수 있다.
**주요 기능**
✔ 오디오 파일(WAV, AIFF 등) 재생
✔ 마이크 입력 받아 녹음
✔ 오디오 데이터 변환
---
## **2. 주요 클래스 및 메서드 정리**
### **(1) `AudioSystem` 클래스 (오디오 시스템 제어)**
| 메서드 | 설명 |
|--------|------------------------------|
| `getClip()` | 짧은 오디오를 재생하는 `Clip` 객체 반환 |
| `getAudioInputStream(File file)` | 오디오 파일을 `AudioInputStream`으로 가져오기 |
| `getMixerInfo()` | 사용 가능한 믹서(입출력 장치) 목록 가져오기 |
| `getLine(DataLine.Info info)` | 특정 오디오 라인(스피커, 마이크 등) 가져오기 |
---
### **(2) `Clip` 클래스 (짧은 오디오 재생)**
| 메서드 | 설명 |
|--------|------------------------------|
| `open(AudioInputStream stream)` | 오디오 데이터를 로드하여 준비 |
| `start()` | 오디오 재생 시작 |
| `stop()` | 오디오 재생 중지 |
| `loop(int count)` | 오디오를 반복 재생 |
---
### **(3) `SourceDataLine` 클래스 (실시간 오디오 출력)**
| 메서드 | 설명 |
|--------|------------------------------|
| `open(AudioFormat format)` | 특정 형식의 오디오를 출력하도록 설정 |
| `write(byte[] data, int offset, int length)` | 오디오 데이터를 출력(재생) |
| `start()` | 오디오 출력 시작 |
| `stop()` | 오디오 출력 중지 |
---
### **(4) `TargetDataLine` 클래스 (마이크 입력 녹음)**
| 메서드 | 설명 |
|--------|------------------------------|
| `open(AudioFormat format)` | 특정 형식의 오디오를 입력받도록 설정 |
| `start()` | 녹음 시작 |
| `read(byte[] buffer, int offset, int length)` | 마이크 입력 데이터를 읽기 |
| `stop()` | 녹음 중지 |
---
### **(5) `AudioInputStream` 클래스 (오디오 데이터 스트림)**
| 메서드 | 설명 |
|--------|------------------------------|
| `read(byte[] buffer, int offset, int length)` | 오디오 데이터를 읽어오기 |
| `skip(long n)` | 지정된 바이트 수만큼 건너뛰기 |
| `close()` | 스트림 닫기 |
---
## **3. 자바로 오디오 재생하기**
### **✔ WAV 파일 재생 예제 (`Clip` 사용)**
```java
import javax.sound.sampled.*;
import java.io.File;
public class AudioPlayer {
public static void main(String[] args) {
try {
File audioFile = new File("sound.wav"); // 재생할 파일
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start(); // 재생 시작
Thread.sleep(clip.getMicrosecondLength() / 1000); // 재생 시간만큼 대기
clip.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
**`Clip`을 사용하면 짧은 오디오 파일을 쉽게 재생할 수 있다.**
---
## **4. 자바로 마이크 녹음하기**
### **✔ 마이크 입력 받아 WAV 파일 저장**
```java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class AudioRecorder {
public static void main(String[] args) {
try {
AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
microphone.open(format);
microphone.start();
File outputFile = new File("recorded.wav");
AudioInputStream audioStream = new AudioInputStream(microphone);
System.out.println("녹음 시작! 5초간 녹음합니다...");
AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, outputFile);
Thread.sleep(5000);
microphone.stop();
microphone.close();
System.out.println("녹음 완료! 파일 저장: " + outputFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
**마이크로 5초 동안 녹음하고 WAV 파일로 저장한다.**
---
## **5. 자바에서 실시간 오디오 재생**
### **✔ `SourceDataLine`을 사용한 실시간 오디오 출력**
```java
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class RealTimeAudioPlayer {
public static void main(String[] args) {
try {
File audioFile = new File("sound.wav");
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(format);
sourceLine.start();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = audioStream.read(buffer)) != -1) {
sourceLine.write(buffer, 0, bytesRead);
}
sourceLine.drain();
sourceLine.close();
audioStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
**오디오 데이터를 한 번에 조금씩 읽어 재생하는 방식으로, 큰 파일도 재생할 수 있다.**
---
## **6. 정리**
**`javax.sound.sampled`는 자바에서 오디오를 다루는 표준 API이다!**
**파일 재생 (`Clip`) / 실시간 출력 (`SourceDataLine`) / 마이크 입력 (`TargetDataLine`) 등 다양한 기능 제공**
**오디오 포맷 변환, 녹음 및 편집도 가능**
✅ **자바로 간단한 음악 플레이어나 음성 녹음 프로그램을 만들 수 있다!**