AudioSystem: isLineSupported(Info info) : AudioSystem « javax.sound.sampled « Java by API

Java by API
1. com.sun.image.codec.jpeg
2. java.applet
3. java.awt
4. java.awt.datatransfer
5. java.awt.dnd
6. java.awt.event
7. java.awt.font
8. java.awt.geom
9. java.awt.im.spi
10. java.awt.image
11. java.awt.print
12. java.beans
13. java.beans.beancontext
14. java.io
15. java.lang
16. java.lang.annotation
17. java.lang.instrument
18. java.lang.management
19. java.lang.ref
20. java.lang.reflect
21. java.math
22. java.net
23. java.nio
24. java.nio.channels
25. java.nio.charset
26. java.rmi.dgc
27. java.rmi.server
28. java.security
29. java.security.cert
30. java.security.spec
31. java.sql
32. java.text
33. java.text.spi
34. java.util
35. java.util.concurrent
36. java.util.concurrent.atomic
37. java.util.concurrent.locks
38. java.util.jar
39. java.util.logging
40. java.util.prefs
41. java.util.regex
42. java.util.spi
43. java.util.zip
44. javax.accessibility
45. javax.activation
46. javax.annotation.security
47. javax.comm
48. javax.crypto
49. javax.crypto.spec
50. javax.ejb
51. javax.imageio
52. javax.imageio.event
53. javax.jws
54. javax.mail
55. javax.mail.internet
56. javax.media.jai
57. javax.microedition.io
58. javax.microedition.lcdui
59. javax.microedition.media
60. javax.microedition.media.control
61. javax.microedition.midlet
62. javax.microedition.pim
63. javax.microedition.rms
64. javax.naming
65. javax.naming.directory
66. javax.naming.event
67. javax.naming.ldap
68. javax.naming.spi
69. javax.net
70. javax.net.ssl
71. javax.persistence
72. javax.print
73. javax.print.attribute
74. javax.print.attribute.standard
75. javax.print.event
76. javax.script
77. javax.servlet
78. javax.servlet.http
79. javax.sound.midi
80. javax.sound.sampled
81. javax.sql
82. javax.sql.rowset
83. javax.swing
84. javax.swing.border
85. javax.swing.colorchooser
86. javax.swing.event
87. javax.swing.filechooser
88. javax.swing.plaf.basic
89. javax.swing.plaf.metal
90. javax.swing.plaf.synth
91. javax.swing.table
92. javax.swing.text
93. javax.swing.text.html
94. javax.swing.text.html.parser
95. javax.swing.text.rtf
96. javax.swing.tree
97. javax.swing.undo
98. javax.tools
99. javax.transaction
100. javax.xml
101. javax.xml.bind
102. javax.xml.bind.annotation
103. javax.xml.crypto.dsig
104. javax.xml.crypto.dsig.keyinfo
105. javax.xml.namespace
106. javax.xml.parsers
107. javax.xml.soap
108. javax.xml.stream
109. javax.xml.stream.events
110. javax.xml.transform
111. javax.xml.transform.dom
112. javax.xml.transform.stream
113. javax.xml.validation
114. javax.xml.ws
115. javax.xml.xpath
116. junit.extensions
117. junit.framework
118. junit.textui
119. org.apache.commons.lang
120. org.apache.commons.lang.builder
121. org.apache.commons.lang.exception
122. org.apache.commons.lang.time
123. org.apache.commons.logging
124. org.apache.commons.math
125. org.eclipse.jface.action
126. org.eclipse.jface.dialogs
127. org.eclipse.jface.operation
128. org.eclipse.jface.viewers
129. org.eclipse.jface.window
130. org.eclipse.jface.wizard
131. org.eclipse.swt
132. org.eclipse.swt.browser
133. org.eclipse.swt.custom
134. org.eclipse.swt.dnd
135. org.eclipse.swt.events
136. org.eclipse.swt.graphics
137. org.eclipse.swt.layout
138. org.eclipse.swt.ole.win32
139. org.eclipse.swt.printing
140. org.eclipse.swt.program
141. org.eclipse.swt.widgets
142. org.junit
143. org.w3c.dom
144. org.xml.sax
145. org.xml.sax.helpers
146. sun.audio
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java by API » javax.sound.sampled » AudioSystem 
AudioSystem: isLineSupported(Info info)
 
/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.com/javaexamples3.
 */

import java.io.IOException;
import java.net.URL;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaEventListener;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * This class plays sounds streaming from a URL: it does not have to preload the
 * entire sound into memory before playing it. It is a command-line application
 * with no gui. It includes code to convert ULAW and ALAW audio formats to PCM
 * so they can be played. Use the -m command-line option before MIDI files.
 */
public class Main {
  // Create a URL from the command-line argument and pass it to the
  // right static method depending on the presence of the -m (MIDI) option.
  public static void main(String[] argsthrows Exception {
    if (args[0].equals("-m"))
      streamMidiSequence(new URL(args[1]));
    else
      streamSampledAudio(new URL(args[0]));

    // Exit explicitly.
    // This is needed because the audio system starts background threads.
    System.exit(0);
  }

  /** Read sampled audio data from the specified URL and play it */
  public static void streamSampledAudio(URL urlthrows IOException, UnsupportedAudioFileException,
      LineUnavailableException {
    AudioInputStream ain = null// We read audio data from here
    SourceDataLine line = null// And write it here.

    try {
      // Get an audio input stream from the URL
      ain = AudioSystem.getAudioInputStream(url);

      // Get information about the format of the stream
      AudioFormat format = ain.getFormat();
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

      // If the format is not supported directly (i.e. if it is not PCM
      // encoded, then try to transcode it to PCM.
      if (!AudioSystem.isLineSupported(info)) {
        // This is the PCM format we want to transcode to.
        // The parameters here are audio format details that you
        // shouldn't need to understand for casual use.
        AudioFormat pcm = new AudioFormat(format.getSampleRate()16, format.getChannels(), true,
            false);

        // Get a wrapper stream around the input stream that does the
        // transcoding for us.
        ain = AudioSystem.getAudioInputStream(pcm, ain);

        // Update the format and info variables for the transcoded data
        format = ain.getFormat();
        info = new DataLine.Info(SourceDataLine.class, format);
      }

      // Open the line through which we'll play the streaming audio.
      line = (SourceDataLineAudioSystem.getLine(info);
      line.open(format);

      // Allocate a buffer for reading from the input stream and writing
      // to the line. Make it large enough to hold 4k audio frames.
      // Note that the SourceDataLine also has its own internal buffer.
      int framesize = format.getFrameSize();
      byte[] buffer = new byte[1024 * framesize]// the buffer
      int numbytes = 0// how many bytes

      // We haven't started the line yet.
      boolean started = false;

      for (;;) { // We'll exit the loop when we reach the end of stream
        // First, read some bytes from the input stream.
        int bytesread = ain.read(buffer, numbytes, buffer.length - numbytes);
        // If there were no more bytes to read, we're done.
        if (bytesread == -1)
          break;
        numbytes += bytesread;

        // Now that we've got some audio data, to write to the line,
        // start the line, so it will play that data as we write it.
        if (!started) {
          line.start();
          started = true;
        }

        // We must write bytes to the line in an integer multiple of
        // the framesize. So figure out how many bytes we'll write.
        int bytestowrite = (numbytes / framesize* framesize;

        // Now write the bytes. The line will buffer them and play
        // them. This call will block until all bytes are written.
        line.write(buffer, 0, bytestowrite);

        // If we didn't have an integer multiple of the frame size,
        // then copy the remaining bytes to the start of the buffer.
        int remaining = numbytes - bytestowrite;
        if (remaining > 0)
          System.arraycopy(buffer, bytestowrite, buffer, 0, remaining);
        numbytes = remaining;
      }

      // Now block until all buffered sound finishes playing.
      line.drain();
    finally // Always relinquish the resources we use
      if (line != null)
        line.close();
      if (ain != null)
        ain.close();
    }
  }

  // A MIDI protocol constant that isn't defined by javax.sound.midi
  public static final int END_OF_TRACK = 47;

  /* MIDI or RMF data from the specified URL and play it */
  public static void streamMidiSequence(URL urlthrows IOException, InvalidMidiDataException,
      MidiUnavailableException {
    Sequencer sequencer = null// Converts a Sequence to MIDI events
    Synthesizer synthesizer = null// Plays notes in response to MIDI events

    try {
      // Create, open, and connect a Sequencer and Synthesizer
      // They are closed in the finally block at the end of this method.
      sequencer = MidiSystem.getSequencer();
      sequencer.open();
      synthesizer = MidiSystem.getSynthesizer();
      synthesizer.open();
      sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());

      // Specify the InputStream to stream the sequence from
      sequencer.setSequence(url.openStream());

      // This is an arbitrary object used with wait and notify to
      // prevent the method from returning before the music finishes
      final Object lock = new Object();

      // Register a listener to make the method exit when the stream is
      // done. See Object.wait() and Object.notify()
      sequencer.addMetaEventListener(new MetaEventListener() {
        public void meta(MetaMessage e) {
          if (e.getType() == END_OF_TRACK) {
            synchronized (lock) {
              lock.notify();
            }
          }
        }
      });

      // Start playing the music
      sequencer.start();

      // Now block until the listener above notifies us that we're done.
      synchronized (lock) {
        while (sequencer.isRunning()) {
          try {
            lock.wait();
          catch (InterruptedException e) {
          }
        }
      }
    finally {
      // Always relinquish the sequencer, so others can use it.
      if (sequencer != null)
        sequencer.close();
      if (synthesizer != null)
        synthesizer.close();
    }
  }
}

   
  
Related examples in the same category
1. AudioSystem: getLine(Info info)
2. AudioSystem: getAudioInputStream(File file)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.