Archive

Articles taggués ‘Snippet’

Audio snippet code in Java

24/03/2010
Commentaires fermés

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 !


import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import javax.sound.sampled.SourceDataLine;

public class AudioInfo {

    public static void main(final String[] args) {
        try {
            AudioFileFormat format = AudioSystem.getAudioFileFormat(new File("Recharger.wav"));
            System.out.println("format: " + format);

            Mixer.Info[] infos = AudioSystem.getMixerInfo();
            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            Line.Info lineInfo = null;
            for (int i = 0; i < infos.length; ++i) {
                Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);
                System.out.println("Target lines infos");
                Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);
                for (int l = 0; l < lineInfos.length; ++l) {
                    System.out.println("Line Info " + l + " - " + lineInfos[l]);
                    lineInfo = lineInfos[l];
                }
            }

            SourceDataLine sourceLine;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format.getFormat()); // format is an AudioFormat object
            if (AudioSystem.isLineSupported(info)) {
                // Obtain and open the line.
                try {
                    sourceLine = (SourceDataLine) AudioSystem.getLine(info);
                    sourceLine.open(format.getFormat());
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println("Line is not supported");
            }

            Port targetLine;
            if (AudioSystem.isLineSupported(Port.Info.SPEAKER)) {
                try {
                    targetLine = (Port) AudioSystem.getLine(Port.Info.SPEAKER);
                    targetLine.open();
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println("SPEAKER Line is not supported");
            }

        } catch (Exception ex) {
            //UnsupportedAudioFile... &amp; IO...
            ex.printStackTrace();
        }
    }
}

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

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;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SoundPlayer extends JFrame implements Runnable {

    private final File currentDir; // Current directory
    private String oldFilename; // Last selected file name
    private final JComboBox soundChoice; // Dropdown list of files
    private final JButton play; // PLAY button
    private AudioInputStream source; // Stream for the sound file
    private SourceDataLine sourceLine; // The speaker output line
    private byte[] soundData; // Buffer to hold samples
    private int bufferSize; // Buffer size in bytes
    private Thread thread; // Playing thread
    private boolean playing = false; // Thread control

    public SoundPlayer() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Sound File Player");
        setSize(250, 100);

        // Get the sounds file names from current directory
        currentDir = new File(System.getProperty("user.dir"));
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(final File directory, final String filename) {
                String name = filename.toLowerCase();
                return name.endsWith(".au") || name.endsWith(".aif") || name.endsWith(".wav");
            }
        };
        String soundFiles[] = currentDir.list(filter);
        if (soundFiles == null || soundFiles.length == 0) {
            JOptionPane.showMessageDialog(this, "No sound files .:. terminating...", "Sound Files Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        soundChoice = new JComboBox(soundFiles);
        soundChoice.setSelectedIndex(0);
        newSound(soundFiles[0]);
        oldFilename = soundFiles[0];

        soundChoice.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                newSound((String) soundChoice.getSelectedItem());
            }
        });

        // Set up the PLAY button to play the current sound file
        play = new JButton("PLAY");
        play.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (e.getActionCommand().equals("PLAY")) {
                    startPlay();
                    play.setText("STOP");
                } else {
                    stopPlay();
                    play.setText("PLAY");
                }
            }
        });
        Container content = getContentPane();
        content.add(soundChoice);
        content.add(play, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(final String[] args) {
        new SoundPlayer();
    }

    public void newSound(final String filename) {
        File soundFile = new File(currentDir, filename);

        // We may have played a file already
        if (sourceLine != null) {// If we have a line
            if (sourceLine.isActive()) {
                sourceLine.stop(); // ...stop it
            }
            play.setText("PLAY"); // Ensure button is PLAY
        }

        // Now try for a stream and a line
        try {
            AudioInputStream newSource = AudioSystem.getAudioInputStream(soundFile);

            if (newSource.markSupported()) {
                newSource.mark(Integer.MAX_VALUE); // mark the start for later reset
            }

            AudioFormat format = newSource.getFormat(); // Get the audio format
            DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format);
            if (AudioSystem.isLineSupported(sourceInfo)) { // If the line type is supported
                // Get a new line
                sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);
                bufferSize = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);
                sourceLine.open(format, bufferSize); // Open the line
                source = newSource; // New line is OK so save it
                soundData = new byte[bufferSize]; // Create the buffer for read
                oldFilename = filename; // Save the current file name
            } else {
                JOptionPane.showMessageDialog(null, "Line not supported", "Line NotSupported", JOptionPane.WARNING_MESSAGE);
                soundChoice.setSelectedItem(oldFilename); // Restore the old selection
            }
        } catch (UnsupportedAudioFileException e) {
            JOptionPane.showMessageDialog(null, "File not supported", "Unsupported File Type", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (LineUnavailableException e) {
            JOptionPane.showMessageDialog(null, "Line not available", "Line Error", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "I/O Error creating stream", "I/O Error", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        }
    }

    // Start playing the current file
    public void startPlay() {
        if (sourceLine == null) {// Verify we have a line
            JOptionPane.showMessageDialog(null, "No line available", "Play Problem", JOptionPane.WARNING_MESSAGE);
            return;
        }
        thread = new Thread(this); // Create the playing thread
        playing = true; // Set the control to true
        thread.start(); // Start the thread
    }

    // Stop playing the current file
    public void stopPlay() {
        playing = false;
    }

    // The playing thread
    public void run() {
        sourceLine.start(); // Start the line
        int byteCount = 0; // Bytes read
        try {
            while (playing) { // Continue while true
                byteCount = source.read(soundData, 0, soundData.length); // Read the stream

                if (byteCount == -1) { // If it's the end of input
                    if (source.markSupported()) {
                        source.reset(); // ...put it back to the start
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                    } else {
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                        source.close();
                        newSound((String) soundChoice.getSelectedItem());
                    }
                    break; // then stop playing
                }
                sourceLine.write(soundData, 0, byteCount); // Write the array to the line
            }
        } catch (IOException e) { // For the stream read operation
            System.err.println(e);
        }
        sourceLine.stop(); // Stop the line
        play.setText("PLAY"); // Reset the button text
    }
}

Java , ,