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 java.io.IOException;
21 import java.util.logging.Logger;
22 import javax.sound.sampled.AudioFormat;
23 import javax.sound.sampled.AudioSystem;
24 import javax.sound.sampled.LineUnavailableException;
25 import javax.sound.sampled.SourceDataLine;
27 import net.pterodactylus.sonitus.data.Metadata;
28 import net.pterodactylus.sonitus.data.Sink;
29 import net.pterodactylus.sonitus.data.Source;
31 import com.google.common.base.Preconditions;
34 * {@link Sink} implementation that uses the JDK’s {@link AudioSystem} to play
35 * all {@link Source}s.
37 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
39 public class AudioSink implements Sink {
42 private static final Logger logger = Logger.getLogger(AudioSink.class.getName());
44 /** The current metadata. */
45 private Metadata metadata;
47 /** The audio output. */
48 private SourceDataLine sourceDataLine;
55 public void open(Metadata metadata) throws IOException {
56 Preconditions.checkArgument(metadata.encoding().equalsIgnoreCase("PCM"), "source must be PCM-encoded");
57 AudioFormat audioFormat = new AudioFormat(metadata.frequency(), 16, metadata.channels(), true, false);
59 sourceDataLine = AudioSystem.getSourceDataLine(audioFormat);
60 sourceDataLine.open(audioFormat);
61 sourceDataLine.start();
62 } catch (LineUnavailableException e) {
64 throw new IOException(e);
70 sourceDataLine.stop();
71 sourceDataLine.close();
75 public void metadataUpdated(Metadata metadata) {
76 logger.info(String.format("Now playing %s.", metadata));
80 public void process(byte[] buffer) {
81 sourceDataLine.write(buffer, 0, buffer.length);
82 logger.finest(String.format("AudioSink: Wrote %d Bytes.", buffer.length));