-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBruitage.java
More file actions
71 lines (60 loc) · 2.04 KB
/
Bruitage.java
File metadata and controls
71 lines (60 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* @author Alain Barbier alias "Metroidzeta"
*
* Pour compiler avec Windows, GNU/Linux et MacOS :
* > javac *.java
*
* Pour exécuter :
* > java Motus
*
* Pour créer un jar de l'application :
* > jar cvmf MANIFEST.MF Motus.jar *.class bruitages/* listesMots/*
*/
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Bruitage {
private static final String DOSSIER = "bruitages";
private final Clip son;
public Bruitage(String nomFichier) {
validerArguments(nomFichier);
son = initClip(nomFichier);
if (son == null) throw new IllegalStateException("Impossible de charger le fichier audio : " + nomFichier);
}
private static void validerArguments(String nomFichier) {
if (nomFichier == null || nomFichier.isBlank()) throw new IllegalArgumentException("nomFichier null ou vide");
}
private Clip initClip(String nomFichier) {
Path chemin = Paths.get(DOSSIER, nomFichier);
try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(chemin.toFile())) { // try-with-resources
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
System.err.println("Erreur lors du chargement du bruitage : " + chemin);
e.printStackTrace();
return null;
}
}
/*** Autre méthodes ***/
public void play() {
if (son != null && son.isOpen()) {
son.setFramePosition(0); // positionner le lecteur au début
son.start(); // jouer le bruitage
}
}
public void stop() {
if (son != null && son.isRunning()) son.stop();
}
public boolean isRunning() {
return son != null && son.isRunning();
}
public void close() {
if (son != null && son.isOpen()) son.close();
}
}