Thursday, June 23, 2016

71. AudioClip

With AudioClip we can load audio into memory. For large files we should use streaming Media API.


In Audacity (audio editor), selecting Generate menu and Chirp... option, we can generate a chirp sound and then export in to a wav file. The default length is 30 second which should be OK. Of course it does not matter what the sound is, as long as it is a small file. We place the file in the src folder.


Rather than using the full path, we can create a URL and then convert it to String in the AudioClip constructor. If the Play button is pressed, we call the play method for the AudioClip object.


package ex71;

import java.net.URL;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;

public class Ex71 extends Application {

    private final String style =
            "-fx-font-family: Georgia; -fx-font-size: 32;"
            +"-fx-text-fill: purple;";

    @Override
    public void start(Stage stage) {

        URL chirpURL = getClass().getResource("/chirp.wav");
        AudioClip chirp = new AudioClip(chirpURL.toString());
        
        Button button = new Button("Play");
        button.setStyle(style);
        button.setOnAction(e->chirp.play());
        
        VBox vbox = new VBox(button);
        vbox.setAlignment(Pos.CENTER);
        vbox.setStyle("-fx-background-color: lime");

        Scene scene = new Scene(vbox, 400, 300);
        stage.setTitle("Example 71. AudioClip");

        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}

This is the output:


No comments:

Post a Comment