a0a4c6a255fb6b319b6b2cbf46073656584d428c
[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 import com.google.common.eventbus.EventBus;
43
44 /**
45  * {@link Sink} implementation that uses the JDK’s {@link AudioSystem} to play
46  * all {@link Source}s.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class AudioSink implements Sink {
51
52         /** The logger. */
53         private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
54
55         /** The event bus. */
56         private final EventBus eventBus;
57
58         /** The volume fader. */
59         private final Fader volumeFader;
60
61         /** The “mute” switch. */
62         private final Switch muteSwitch;
63
64         /** The current metadata. */
65         private Metadata metadata;
66
67         /** The audio output. */
68         private SourceDataLine sourceDataLine;
69
70         /** A buffered output stream to ensure correct writing to the source data line. */
71         private OutputStream sourceDataLineOutputStream = new IntegralWriteOutputStream(new OutputStream() {
72
73                 @Override
74                 public void write(int b) throws IOException {
75                 }
76
77                 @Override
78                 public void write(byte[] b) throws IOException {
79                         write(b, 0, b.length);
80                 }
81
82                 @Override
83                 public void write(byte[] b, int off, int len) throws IOException {
84                         if (sourceDataLine != null) {
85                                 sourceDataLine.write(b, off, len);
86                         }
87                 }
88         }, 1024);
89
90         /**
91          * Creates a new audio sink.
92          *
93          * @param eventBus
94          *              The event bus
95          */
96         public AudioSink(EventBus eventBus) {
97                 this.eventBus = eventBus;
98                 volumeFader = new Fader("Volume") {
99
100                         @Override
101                         protected void valueSet(Double value) {
102                                 if (sourceDataLine != null) {
103                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
104                                         volumeControl.setValue((float) (value * volumeControl.getMaximum()));
105                                 }
106                         }
107                 };
108                 muteSwitch = new Switch("Mute") {
109
110                         private float previousValue;
111
112                         @Override
113                         protected void valueSet(Boolean value) {
114                                 if (sourceDataLine != null) {
115                                         FloatControl volumeControl = (FloatControl) sourceDataLine.getControl(VOLUME);
116                                         if (value) {
117                                                 previousValue = volumeControl.getValue();
118                                                 volumeControl.setValue(0);
119                                         } else {
120                                                 volumeControl.setValue(previousValue);
121                                         }
122                                 }
123                         }
124                 };
125         }
126
127         //
128         // CONTROLLED METHODS
129         //
130
131         @Override
132         public String name() {
133                 return "Audio Output";
134         }
135
136         @Override
137         public Metadata metadata() {
138                 return metadata;
139         }
140
141         @Override
142         public List<Controller<?>> controllers() {
143                 return Arrays.<Controller<?>>asList(volumeFader, muteSwitch);
144         }
145
146         //
147         // SINK METHODS
148         //
149
150         @Override
151         public void open(Metadata metadata) throws IOException {
152                 Preconditions.checkArgument(metadata.encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
153                 AudioFormat audioFormat = new AudioFormat(metadata.frequency(), 16, metadata.channels(), true, false);
154                 try {
155                         sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
156                         sourceDataLine.open(audioFormat);
157                         sourceDataLine.start();
158                 } catch (LineUnavailableException e) {
159                         /* TODO */
160                         throw new IOException(e);
161                 }
162         }
163
164         @Override
165         public void close() {
166                 sourceDataLine.stop();
167                 sourceDataLine.close();
168         }
169
170         @Override
171         public void metadataUpdated(Metadata metadata) {
172                 logger.info(String.format("Now playing %s.", metadata));
173                 this.metadata = metadata;
174         }
175
176         @Override
177         public void process(byte[] buffer) throws IOException {
178                 sourceDataLineOutputStream.write(buffer);
179                 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));
180         }
181
182 }