Search in sources :

Example 51 with AudioFormat

use of javax.sound.sampled.AudioFormat in project ant by apache.

the class AntSoundPlayer method play.

/**
 * Plays the file for duration milliseconds or loops.
 */
private void play(Project project, File file, int loops, Long duration) {
    Clip audioClip = null;
    AudioInputStream audioInputStream = null;
    try {
        audioInputStream = AudioSystem.getAudioInputStream(file);
    } catch (UnsupportedAudioFileException uafe) {
        project.log("Audio format is not yet supported: " + uafe.getMessage());
    } catch (IOException ioe) {
        // NOSONAR
        ioe.printStackTrace();
    }
    if (audioInputStream != null) {
        AudioFormat format = audioInputStream.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format, AudioSystem.NOT_SPECIFIED);
        try {
            try {
                audioClip = (Clip) AudioSystem.getLine(info);
                audioClip.addLineListener(this);
                audioClip.open(audioInputStream);
            } catch (LineUnavailableException e) {
                project.log("The sound device is currently unavailable");
                return;
            } catch (IOException e) {
                // NOSONAR
                e.printStackTrace();
            }
            if (duration != null) {
                playClip(audioClip, duration);
            } else {
                playClip(audioClip, loops);
            }
            if (audioClip != null) {
                audioClip.drain();
            }
        } finally {
            FileUtils.close(audioClip);
        }
    } else {
        project.log("Can't get data from file " + file.getName());
    }
}
Also used : Clip(javax.sound.sampled.Clip) AudioInputStream(javax.sound.sampled.AudioInputStream) UnsupportedAudioFileException(javax.sound.sampled.UnsupportedAudioFileException) DataLine(javax.sound.sampled.DataLine) LineUnavailableException(javax.sound.sampled.LineUnavailableException) IOException(java.io.IOException) AudioFormat(javax.sound.sampled.AudioFormat)

Example 52 with AudioFormat

use of javax.sound.sampled.AudioFormat in project java-sdk by watson-developer-cloud.

the class MicrophoneWithWebSocketsExample method main.

/**
 * The main method.
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(final String[] args) throws Exception {
    SpeechToText service = new SpeechToText();
    service.setUsernameAndPassword("<username>", "<password>");
    // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
    int sampleRate = 16000;
    AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    if (!AudioSystem.isLineSupported(info)) {
        System.out.println("Line not supported");
        System.exit(0);
    }
    TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
    line.start();
    AudioInputStream audio = new AudioInputStream(line);
    RecognizeOptions options = new RecognizeOptions.Builder().audio(audio).interimResults(true).timestamps(true).wordConfidence(true).contentType(HttpMediaType.AUDIO_RAW + ";rate=" + sampleRate).build();
    service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() {

        @Override
        public void onTranscription(SpeechRecognitionResults speechResults) {
            System.out.println(speechResults);
        }
    });
    System.out.println("Listening to your voice for the next 30s...");
    Thread.sleep(30 * 1000);
    // closing the WebSockets underlying InputStream will close the WebSocket itself.
    line.stop();
    line.close();
    System.out.println("Fin.");
}
Also used : BaseRecognizeCallback(com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback) TargetDataLine(javax.sound.sampled.TargetDataLine) DataLine(javax.sound.sampled.DataLine) TargetDataLine(javax.sound.sampled.TargetDataLine) AudioInputStream(javax.sound.sampled.AudioInputStream) AudioFormat(javax.sound.sampled.AudioFormat) SpeechRecognitionResults(com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults) RecognizeOptions(com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions)

Example 53 with AudioFormat

use of javax.sound.sampled.AudioFormat in project Symphony by Vazkii.

the class JavaSoundAudioDevice method test.

/**
 * Runs a short test by playing a short silent sound.
 */
public void test() throws JavaLayerException {
    try {
        open(new AudioFormat(22050, 16, 1, true, false));
        short[] data = new short[22050 / 10];
        write(data, 0, data.length);
        flush();
        close();
    } catch (RuntimeException ex) {
        throw new JavaLayerException("Device test failed: " + ex);
    }
}
Also used : AudioFormat(javax.sound.sampled.AudioFormat) JavaLayerException(vazkii.symphony.lib.javazoom.jl.decoder.JavaLayerException)

Example 54 with AudioFormat

use of javax.sound.sampled.AudioFormat in project Symphony by Vazkii.

the class JavaSoundAudioDevice method getSourceLineInfo.

protected DataLine.Info getSourceLineInfo() {
    AudioFormat fmt = getAudioFormat();
    // DataLine.Info info = new DataLine.Info(SourceDataLine.class, fmt, 4000);
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, fmt);
    return info;
}
Also used : DataLine(javax.sound.sampled.DataLine) SourceDataLine(javax.sound.sampled.SourceDataLine) AudioFormat(javax.sound.sampled.AudioFormat)

Example 55 with AudioFormat

use of javax.sound.sampled.AudioFormat in project javacv by bytedeco.

the class JavaFxPlayVideoAndAudio method start.

@Override
public void start(Stage primaryStage) throws Exception {
    StackPane root = new StackPane();
    ImageView imageView = new ImageView();
    root.getChildren().add(imageView);
    imageView.fitWidthProperty().bind(primaryStage.widthProperty());
    imageView.fitHeightProperty().bind(primaryStage.heightProperty());
    Scene scene = new Scene(root, 640, 480);
    primaryStage.setTitle("Video + audio");
    primaryStage.setScene(scene);
    primaryStage.show();
    playThread = new Thread(() -> {
        try {
            String videoFilename = getParameters().getRaw().get(0);
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFilename);
            grabber.start();
            primaryStage.setWidth(grabber.getImageWidth());
            primaryStage.setHeight(grabber.getImageHeight());
            AudioFormat audioFormat = new AudioFormat(grabber.getSampleRate(), 16, grabber.getAudioChannels(), true, true);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            SourceDataLine soundLine = (SourceDataLine) AudioSystem.getLine(info);
            soundLine.open(audioFormat);
            soundLine.start();
            Java2DFrameConverter converter = new Java2DFrameConverter();
            ExecutorService executor = Executors.newSingleThreadExecutor();
            while (!Thread.interrupted()) {
                Frame frame = grabber.grab();
                if (frame == null) {
                    break;
                }
                if (frame.image != null) {
                    Image image = SwingFXUtils.toFXImage(converter.convert(frame), null);
                    Platform.runLater(() -> {
                        imageView.setImage(image);
                    });
                } else if (frame.samples != null) {
                    ShortBuffer channelSamplesShortBuffer = (ShortBuffer) frame.samples[0];
                    channelSamplesShortBuffer.rewind();
                    ByteBuffer outBuffer = ByteBuffer.allocate(channelSamplesShortBuffer.capacity() * 2);
                    for (int i = 0; i < channelSamplesShortBuffer.capacity(); i++) {
                        short val = channelSamplesShortBuffer.get(i);
                        outBuffer.putShort(val);
                    }
                    /**
                     * We need this because soundLine.write ignores
                     * interruptions during writing.
                     */
                    try {
                        executor.submit(() -> {
                            soundLine.write(outBuffer.array(), 0, outBuffer.capacity());
                            outBuffer.clear();
                        }).get();
                    } catch (InterruptedException interruptedException) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
            executor.shutdownNow();
            executor.awaitTermination(10, TimeUnit.SECONDS);
            soundLine.stop();
            grabber.stop();
            grabber.release();
            Platform.exit();
        } catch (Exception exception) {
            LOG.log(Level.SEVERE, null, exception);
            System.exit(1);
        }
    });
    playThread.start();
}
Also used : Frame(org.bytedeco.javacv.Frame) DataLine(javax.sound.sampled.DataLine) SourceDataLine(javax.sound.sampled.SourceDataLine) Scene(javafx.scene.Scene) Image(javafx.scene.image.Image) ByteBuffer(java.nio.ByteBuffer) FFmpegFrameGrabber(org.bytedeco.javacv.FFmpegFrameGrabber) ExecutorService(java.util.concurrent.ExecutorService) SourceDataLine(javax.sound.sampled.SourceDataLine) ImageView(javafx.scene.image.ImageView) AudioFormat(javax.sound.sampled.AudioFormat) ShortBuffer(java.nio.ShortBuffer) StackPane(javafx.scene.layout.StackPane) Java2DFrameConverter(org.bytedeco.javacv.Java2DFrameConverter)

Aggregations

AudioFormat (javax.sound.sampled.AudioFormat)112 AudioInputStream (javax.sound.sampled.AudioInputStream)43 IOException (java.io.IOException)24 DataLine (javax.sound.sampled.DataLine)21 SourceDataLine (javax.sound.sampled.SourceDataLine)21 AudioFileFormat (javax.sound.sampled.AudioFileFormat)18 UnsupportedAudioFileException (javax.sound.sampled.UnsupportedAudioFileException)18 LineUnavailableException (javax.sound.sampled.LineUnavailableException)17 File (java.io.File)15 InputStream (java.io.InputStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 TargetDataLine (javax.sound.sampled.TargetDataLine)7 MpegAudioFormat (javazoom.spi.mpeg.sampled.file.MpegAudioFormat)7 BufferedInputStream (java.io.BufferedInputStream)6 FileInputStream (java.io.FileInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 DataInputStream (java.io.DataInputStream)5 Vector (java.util.Vector)5 SequenceInputStream (java.io.SequenceInputStream)4 Clip (javax.sound.sampled.Clip)4