d95df6e7d172591da2fe0c9adc79e5bb7a5862ef
[sonitus.git] / src / main / java / net / pterodactylus / sonitus / data / sink / AudioSink.java
1 /*
2  * Sonitus - AudioSink.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sonitus.data.sink;
19
20 import static javax.sound.sampled.FloatControl.Type.VOLUME;
21
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.logging.Logger;
27 import javax.sound.sampled.AudioFormat;
28 import javax.sound.sampled.AudioSystem;
29 import javax.sound.sampled.FloatControl;
30 import javax.sound.sampled.LineUnavailableException;
31 import javax.sound.sampled.SourceDataLine;
32
33 import net.pterodactylus.sonitus.data.Controller;
34 import net.pterodactylus.sonitus.data.Metadata;
35 import net.pterodactylus.sonitus.data.Sink;
36 import net.pterodactylus.sonitus.data.Source;
37 import net.pterodactylus.sonitus.data.controller.Fader;
38 import net.pterodactylus.sonitus.data.controller.Switch;
39 import net.pterodactylus.sonitus.io.IntegralWriteOutputStream;
40
41 import com.google.common.base.Preconditions;
42
43 /**
44  * {@link Sink} implementation that uses the JDK’s {@link AudioSystem} to play
45  * all {@link Source}s.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class AudioSink implements Sink {
50
51         /** The logger. */
52         private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
53
54         /** The volume fader. */
55         private final Fader volumeFader;
56
57         /** The “mute” switch. */
58         private final Switch muteSwitch;
59
60         /** The current metadata. */
61         private Metadata metadata;
62
63         /** The audio output. */
64         private SourceDataLine sourceDataLine;
65
66         /** A buffered output stream to ensure correct writing to the source data line. */
67         private OutputStream sourceDataLineOutputStream = new IntegralWriteOutputStream(new OutputStream() {
68
69                 @Override
70                 public void write(int b) throws IOException {
71                 }
72
73                 @Override
74                 public void write(byte[] b) throws IOException {
75                         write(b, 0, b.length);
76                 }
77
78                 @Override
79                 public void write(byte[] b, int off, int len) throws IOException {
80                         if (sourceDataLine != null) {
81                                 sourceDataLine.write(b, off, len);
82                         }
83                 }
84         }, 1024);
85
86         /** Creates a new audio sink. */
87         public AudioSink() {
88                 super();
89                 volumeFader = new Fader("Volume") {
90
91                         @Override
92                         protected void valueSet(Double value) {
93                                 if (sourceDataLine != null) {
94                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
95                                         volumeControl.setValue((float) (value * volumeControl.getMaximum()));
96                                 }
97                         }
98                 };
99                 muteSwitch = new Switch("Mute") {
100
101                         private float previousValue;
102
103                         @Override
104                         protected void valueSet(Boolean value) {
105                                 if (sourceDataLine != null) {
106                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
107                                         if (value) {
108                                                 previousValue = volumeControl.getValue();
109                                                 volumeControl.setValue(0);
110                                         } else {
111                                                 volumeControl.setValue(previousValue);
112                                         }
113                                 }
114                         }
115                 };
116         }
117
118         //
119         // CONTROLLED METHODS
120         //
121
122         @Override
123         public List<Controller<?>> controllers() {
124                 return Arrays.<Controller<?>>asList(volumeFader, muteSwitch);
125         }
126
127         //
128         // SINK METHODS
129         //
130
131         @Override
132         public void open(Metadata metadata) throws IOException {
133                 Preconditions.checkArgument(metadata.encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
134                 AudioFormat audioFormat = new AudioFormat(metadata.frequency(), 16, metadata.channels(), true, false);
135                 try {
136                         sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
137                         sourceDataLine.open(audioFormat);
138                         sourceDataLine.start();
139                 } catch (LineUnavailableException e) {
140                         /* TODO */
141                         throw new IOException(e);
142                 }
143         }
144
145         @Override
146         public void close() {
147                 sourceDataLine.stop();
148                 sourceDataLine.close();
149         }
150
151         @Override
152         public void metadataUpdated(Metadata metadata) {
153                 logger.info(String.format("Now playing %s.", metadata));
154         }
155
156         @Override
157         public void process(byte[] buffer) throws IOException {
158                 sourceDataLineOutputStream.write(buffer);
159                 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));
160         }
161
162 }