Accueil > Java > Audio snippet code in Java

Audio snippet code in Java

24/03/2010

Here is an example of two simple Java classes that deals with audio streams ! One for retrieving Info, the other for playing sound …

Voici deux petits exemples de classe Java pour gérer des flux audio. L’une affichant les informations, l’autre implémentant un lecteur très minimaliste !

  1. import java.io.File;  
  2.   
  3. import javax.sound.sampled.AudioFileFormat;  
  4. import javax.sound.sampled.AudioSystem;  
  5. import javax.sound.sampled.DataLine;  
  6. import javax.sound.sampled.Line;  
  7. import javax.sound.sampled.LineUnavailableException;  
  8. import javax.sound.sampled.Mixer;  
  9. import javax.sound.sampled.Port;  
  10. import javax.sound.sampled.SourceDataLine;  
  11.   
  12. public class AudioInfo {  
  13.   
  14.     public static void main(final String[] args) {  
  15.         try {  
  16.             AudioFileFormat format = AudioSystem.getAudioFileFormat(new File("Recharger.wav"));  
  17.             System.out.println("format: " + format);  
  18.   
  19.             Mixer.Info[] infos = AudioSystem.getMixerInfo();  
  20.             Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();  
  21.             Line.Info lineInfo = null;  
  22.             for (int i = 0; i < infos.length; ++i) {  
  23.                 Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);  
  24.                 System.out.println("Target lines infos");  
  25.                 Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);  
  26.                 for (int l = 0; l < lineInfos.length; ++l) {  
  27.                     System.out.println("Line Info " + l + " - " + lineInfos[l]);  
  28.                     lineInfo = lineInfos[l];  
  29.                 }  
  30.             }  
  31.   
  32.             SourceDataLine sourceLine;  
  33.             DataLine.Info info = new DataLine.Info(SourceDataLine.class, format.getFormat()); // format is an AudioFormat object  
  34.             if (AudioSystem.isLineSupported(info)) {  
  35.                 // Obtain and open the line.  
  36.                 try {  
  37.                     sourceLine = (SourceDataLine) AudioSystem.getLine(info);  
  38.                     sourceLine.open(format.getFormat());  
  39.                 } catch (LineUnavailableException ex) {  
  40.                     // Handle the error.  
  41.                     ex.printStackTrace();  
  42.                 }  
  43.             } else {  
  44.                 // Handle the error.  
  45.                 System.out.println("Line is not supported");  
  46.             }  
  47.   
  48.             Port targetLine;  
  49.             if (AudioSystem.isLineSupported(Port.Info.SPEAKER)) {  
  50.                 try {  
  51.                     targetLine = (Port) AudioSystem.getLine(Port.Info.SPEAKER);  
  52.                     targetLine.open();  
  53.                 } catch (LineUnavailableException ex) {  
  54.                     // Handle the error.  
  55.                     ex.printStackTrace();  
  56.                 }  
  57.             } else {  
  58.                 // Handle the error.  
  59.                 System.out.println("SPEAKER Line is not supported");  
  60.             }  
  61.   
  62.         } catch (Exception ex) {  
  63.             //UnsupportedAudioFile... &amp; IO...  
  64.             ex.printStackTrace();  
  65.         }  
  66.     }  
  67. }  
  1. import java.awt.BorderLayout;  
  2. import java.awt.Container;  
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.io.File;  
  6. import java.io.FilenameFilter;  
  7. import java.io.IOException;  
  8.   
  9. import javax.sound.sampled.AudioFormat;  
  10. import javax.sound.sampled.AudioInputStream;  
  11. import javax.sound.sampled.AudioSystem;  
  12. import javax.sound.sampled.DataLine;  
  13. import javax.sound.sampled.LineUnavailableException;  
  14. import javax.sound.sampled.SourceDataLine;  
  15. import javax.sound.sampled.UnsupportedAudioFileException;  
  16. import javax.swing.JButton;  
  17. import javax.swing.JComboBox;  
  18. import javax.swing.JFrame;  
  19. import javax.swing.JOptionPane;  
  20.   
  21. public class SoundPlayer extends JFrame implements Runnable {  
  22.   
  23.     private final File currentDir; // Current directory  
  24.     private String oldFilename; // Last selected file name  
  25.     private final JComboBox soundChoice; // Dropdown list of files  
  26.     private final JButton play; // PLAY button  
  27.     private AudioInputStream source; // Stream for the sound file  
  28.     private SourceDataLine sourceLine; // The speaker output line  
  29.     private byte[] soundData; // Buffer to hold samples  
  30.     private int bufferSize; // Buffer size in bytes  
  31.     private Thread thread; // Playing thread  
  32.     private boolean playing = false// Thread control  
  33.   
  34.     public SoundPlayer() {  
  35.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
  36.         setTitle("Sound File Player");  
  37.         setSize(250100);  
  38.   
  39.         // Get the sounds file names from current directory  
  40.         currentDir = new File(System.getProperty("user.dir"));  
  41.         FilenameFilter filter = new FilenameFilter() {  
  42.             public boolean accept(final File directory, final String filename) {  
  43.                 String name = filename.toLowerCase();  
  44.                 return name.endsWith(".au") || name.endsWith(".aif") || name.endsWith(".wav");  
  45.             }  
  46.         };  
  47.         String soundFiles[] = currentDir.list(filter);  
  48.         if (soundFiles == null || soundFiles.length == 0) {  
  49.             JOptionPane.showMessageDialog(this"No sound files .:. terminating...""Sound Files Error", JOptionPane.ERROR_MESSAGE);  
  50.             System.exit(1);  
  51.         }  
  52.         soundChoice = new JComboBox(soundFiles);  
  53.         soundChoice.setSelectedIndex(0);  
  54.         newSound(soundFiles[0]);  
  55.         oldFilename = soundFiles[0];  
  56.   
  57.         soundChoice.addActionListener(new ActionListener() {  
  58.             public void actionPerformed(final ActionEvent e) {  
  59.                 newSound((String) soundChoice.getSelectedItem());  
  60.             }  
  61.         });  
  62.   
  63.         // Set up the PLAY button to play the current sound file  
  64.         play = new JButton("PLAY");  
  65.         play.addActionListener(new ActionListener() {  
  66.             public void actionPerformed(final ActionEvent e) {  
  67.                 if (e.getActionCommand().equals("PLAY")) {  
  68.                     startPlay();  
  69.                     play.setText("STOP");  
  70.                 } else {  
  71.                     stopPlay();  
  72.                     play.setText("PLAY");  
  73.                 }  
  74.             }  
  75.         });  
  76.         Container content = getContentPane();  
  77.         content.add(soundChoice);  
  78.         content.add(play, BorderLayout.SOUTH);  
  79.         setVisible(true);  
  80.     }  
  81.   
  82.     public static void main(final String[] args) {  
  83.         new SoundPlayer();  
  84.     }  
  85.   
  86.     public void newSound(final String filename) {  
  87.         File soundFile = new File(currentDir, filename);  
  88.   
  89.         // We may have played a file already  
  90.         if (sourceLine != null) {// If we have a line  
  91.             if (sourceLine.isActive()) {  
  92.                 sourceLine.stop(); // ...stop it  
  93.             }  
  94.             play.setText("PLAY"); // Ensure button is PLAY  
  95.         }  
  96.   
  97.         // Now try for a stream and a line  
  98.         try {  
  99.             AudioInputStream newSource = AudioSystem.getAudioInputStream(soundFile);  
  100.   
  101.             if (newSource.markSupported()) {  
  102.                 newSource.mark(Integer.MAX_VALUE); // mark the start for later reset  
  103.             }  
  104.   
  105.             AudioFormat format = newSource.getFormat(); // Get the audio format  
  106.             DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format);  
  107.             if (AudioSystem.isLineSupported(sourceInfo)) { // If the line type is supported  
  108.                 // Get a new line  
  109.                 sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);  
  110.                 bufferSize = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);  
  111.                 sourceLine.open(format, bufferSize); // Open the line  
  112.                 source = newSource; // New line is OK so save it  
  113.                 soundData = new byte[bufferSize]; // Create the buffer for read  
  114.                 oldFilename = filename; // Save the current file name  
  115.             } else {  
  116.                 JOptionPane.showMessageDialog(null"Line not supported""Line NotSupported", JOptionPane.WARNING_MESSAGE);  
  117.                 soundChoice.setSelectedItem(oldFilename); // Restore the old selection  
  118.             }  
  119.         } catch (UnsupportedAudioFileException e) {  
  120.             JOptionPane.showMessageDialog(null"File not supported""Unsupported File Type", JOptionPane.WARNING_MESSAGE);  
  121.             soundChoice.setSelectedItem(oldFilename);  
  122.         } catch (LineUnavailableException e) {  
  123.             JOptionPane.showMessageDialog(null"Line not available""Line Error", JOptionPane.WARNING_MESSAGE);  
  124.             soundChoice.setSelectedItem(oldFilename);  
  125.         } catch (IOException e) {  
  126.             JOptionPane.showMessageDialog(null"I/O Error creating stream""I/O Error", JOptionPane.WARNING_MESSAGE);  
  127.             soundChoice.setSelectedItem(oldFilename);  
  128.         }  
  129.     }  
  130.   
  131.     // Start playing the current file  
  132.     public void startPlay() {  
  133.         if (sourceLine == null) {// Verify we have a line  
  134.             JOptionPane.showMessageDialog(null"No line available""Play Problem", JOptionPane.WARNING_MESSAGE);  
  135.             return;  
  136.         }  
  137.         thread = new Thread(this); // Create the playing thread  
  138.         playing = true// Set the control to true  
  139.         thread.start(); // Start the thread  
  140.     }  
  141.   
  142.     // Stop playing the current file  
  143.     public void stopPlay() {  
  144.         playing = false;  
  145.     }  
  146.   
  147.     // The playing thread  
  148.     public void run() {  
  149.         sourceLine.start(); // Start the line  
  150.         int byteCount = 0// Bytes read  
  151.         try {  
  152.             while (playing) { // Continue while true  
  153.                 byteCount = source.read(soundData, 0, soundData.length); // Read the stream  
  154.   
  155.                 if (byteCount == -1) { // If it's the end of input  
  156.                     if (source.markSupported()) {  
  157.                         source.reset(); // ...put it back to the start  
  158.                         sourceLine.drain(); // Play what is left in the buffer  
  159.                         playing = false// Reset the thread control  
  160.                     } else {  
  161.                         sourceLine.drain(); // Play what is left in the buffer  
  162.                         playing = false// Reset the thread control  
  163.                         source.close();  
  164.                         newSound((String) soundChoice.getSelectedItem());  
  165.                     }  
  166.                     break// then stop playing  
  167.                 }  
  168.                 sourceLine.write(soundData, 0, byteCount); // Write the array to the line  
  169.             }  
  170.         } catch (IOException e) { // For the stream read operation  
  171.             System.err.println(e);  
  172.         }  
  173.         sourceLine.stop(); // Stop the line  
  174.         play.setText("PLAY"); // Reset the button text  
  175.     }  
  176. }  

Java , ,

Les commentaires sont fermés.