2 * Sonitus - AudioSink.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sonitus.data.sink;
20 import static com.google.common.base.Preconditions.*;
22 import java.util.logging.Logger;
23 import javax.sound.sampled.AudioFormat;
24 import javax.sound.sampled.AudioSystem;
25 import javax.sound.sampled.LineUnavailableException;
26 import javax.sound.sampled.SourceDataLine;
28 import net.pterodactylus.sonitus.data.ConnectException;
29 import net.pterodactylus.sonitus.data.Connection;
30 import net.pterodactylus.sonitus.data.Format;
31 import net.pterodactylus.sonitus.data.Sink;
32 import net.pterodactylus.sonitus.data.Source;
35 * {@link Sink} implementation that uses the JDK’s {@link
36 * javax.sound.sampled.AudioSystem} to play all {@link net.pterodactylus.sonitus.data.Source}s.
38 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40 public class AudioSink implements Sink {
43 private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
46 public void connect(Source source) throws ConnectException {
47 checkNotNull(source, "source must not be null");
48 checkState(source.format().encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
50 final Format sourceFormat = source.format();
51 AudioFormat audioFormat = new AudioFormat(sourceFormat.frequency(), 16, sourceFormat.channels(), true, false);
53 final SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
54 sourceDataLine.open(audioFormat);
55 sourceDataLine.start();
56 new Thread(new Connection(source) {
59 protected int bufferSize() {
60 return sourceFormat.channels() * sourceFormat.frequency() * 2;
64 protected void feed(byte[] buffer) {
65 sourceDataLine.write(buffer, 0, buffer.length);
66 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));
70 protected void finish() {
71 sourceDataLine.stop();
74 } catch (LineUnavailableException lue1) {
75 throw new ConnectException(lue1);