杰瑞科技汇

Java MediaPlayer如何实现音频视频播放控制?

Of course! The Java MediaPlayer is a fundamental class for playing audio and video files in Java applications. However, it's important to know that there are two main MediaPlayer classes:

Java MediaPlayer如何实现音频视频播放控制?-图1
(图片来源网络,侵删)
  1. javax.media.Player (Java Media Framework - JMF): The older, original framework. It's powerful but complex, has licensing issues, and is now largely considered deprecated and unmaintained. You should avoid it for new projects.
  2. javafx.scene.media.MediaPlayer (JavaFX): The modern, recommended approach for creating rich, interactive desktop applications with Java. It's much easier to use, well-integrated with the JavaFX UI toolkit, and actively maintained.

For this guide, we will focus entirely on the modern and recommended JavaFX MediaPlayer.


JavaFX MediaPlayer (The Modern Way)

The JavaFX MediaPlayer is part of the JavaFX library, which is included with modern Java Development Kits (JDKs) since Java 8. It's designed for creating standalone desktop applications with a graphical user interface (GUI).

Key Components

Before we dive into code, let's understand the main players:

  • Media: Represents the media source. This can be a file path, a URL, or an InputStream. It holds information about the media, like its duration and metadata.
  • MediaPlayer: The engine that plays the Media. It controls playback (play, pause, stop, seek) and manages the state.
  • MediaView: A JavaFX Node (a visual component) that acts as a "viewport" or a "screen" to display the video from the MediaPlayer. You add the MediaView to your scene to see the video.
  • MediaPlayer.Status: An enum representing the current state of the player (e.g., READY, PLAYING, PAUSED, STOPPED, HALTED).
  • MediaPlayer.currentTimeProperty(): A property that tracks the current playback time. You can listen to changes to this property to update a progress bar, for example.

Step-by-Step Guide: Creating a Simple Media Player

Here’s a complete, step-by-step example of a JavaFX application that plays a video file.

Java MediaPlayer如何实现音频视频播放控制?-图2
(图片来源网络,侵删)

Step 1: Project Setup

You need to ensure your project can use JavaFX. If you're using a build tool like Maven or Gradle, this is straightforward.

Maven (pom.xml): You need the JavaFX base and controls modules.

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>21</version> <!-- Or your JDK version -->
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-media</artifactId>
        <version>21</version> <!-- Or your JDK version -->
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>0.0.8</version>
            <executions>
                <execution>
                    <!-- Default configuration for running with: mvn javafx:run -->
                    <id>default-cli</id>
                    <configuration>
                        <mainClass>com.example.mediaplayer.MainApp</mainClass>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Gradle (build.gradle):

plugins {
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.13'
}
group 'com.example'
version '1.0-SNAPSHOT'
repositories {
    mavenCentral()
}
javafx {
    version = "21" // Or your JDK version
    modules = [ 'javafx.controls', 'javafx.media' ]
}
mainClassName = 'com.example.mediaplayer.MainApp'

Step 2: Create a Sample Video File

For this example, create a folder named media in your project's root directory and place a video file inside it (e.g., my-video.mp4).

Your project structure should look something like this:

your-project/
├── media/
│   └── my-video.mp4
├── pom.xml (or build.gradle)
└── src/
    └── main/
        └── java/
            └── com/
                └── example/
                    └── mediaplayer/
                        └── MainApp.java

Step 3: Write the Java Code

This code creates a window with a video player and basic playback controls.

MainApp.java

package com.example.mediaplayer;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.net.MalformedURLException;
public class MainApp extends Application {
    private MediaPlayer mediaPlayer;
    private final DoubleProperty widthRatio = new SimpleDoubleProperty();
    private final DoubleProperty heightRatio = new SimpleDoubleProperty();
    @Override
    public void start(Stage primaryStage) throws MalformedURLException {
        // 1. Create the Media object
        // Get the file from the "media" directory
        String videoPath = new File("media/my-video.mp4").toURI().toString();
        Media media = new Media(videoPath);
        // 2. Create the MediaPlayer
        mediaPlayer = new MediaPlayer(media);
        // 3. Create the MediaView to display the video
        MediaView mediaView = new MediaView(mediaPlayer);
        // --- Controls ---
        Button playButton = new Button(">");
        Button stopButton = new Button("Stop");
        // Time label
        Label timeLabel = new Label();
        timeLabel.textProperty().bind(Bindings.createStringBinding(() -> {
            Duration currentTime = mediaPlayer.getCurrentTime();
            Duration totalTime = mediaPlayer.getTotalDuration();
            return String.format("%s / %s", formatTime(currentTime), formatTime(totalTime));
        }, mediaPlayer.currentTimeProperty(), mediaPlayer.totalDurationProperty()));
        // Time slider
        Slider timeSlider = new Slider();
        timeSlider.setMin(0);
        timeSlider.setMax(mediaPlayer.getTotalDuration().toSeconds());
        timeSlider.valueProperty().bindBidirectional(mediaPlayer.currentTimeProperty());
        timeSlider.setShowTickLabels(true);
        timeSlider.setShowTickMarks(true);
        // Volume slider
        Slider volumeSlider = new Slider();
        volumeSlider.setMin(0);
        volumeSlider.setMax(1);
        volumeSlider.setValue(0.5); // Default volume
        volumeSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
            mediaPlayer.setVolume(newValue.doubleValue());
        });
        // Control Panel Layout
        HBox controlPanel = new HBox(10, playButton, stopButton, timeLabel, timeSlider, volumeSlider);
        controlPanel.setAlignment(Pos.CENTER);
        controlPanel.setPadding(new Insets(10));
        // Main Layout
        VBox root = new VBox(10, mediaView, controlPanel);
        root.setAlignment(Pos.CENTER);
        root.setStyle("-fx-background-color: #3c3c3c; -fx-padding: 20;");
        // 4. Create the Scene and Stage
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setTitle("JavaFX Media Player");
        primaryStage.setScene(scene);
        primaryStage.show();
        // 5. Set up event handlers for the buttons
        playButton.setOnAction(e -> {
            if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
                mediaPlayer.pause();
                playButton.setText(">");
            } else {
                mediaPlayer.play();
                playButton.setText("||");
            }
        });
        stopButton.setOnAction(e -> {
            mediaPlayer.stop();
            playButton.setText(">"); // Reset play button text
        });
        // Clean up resources when the window is closed
        primaryStage.setOnCloseRequest(e -> {
            if (mediaPlayer != null) {
                mediaPlayer.dispose();
            }
        });
    }
    // Helper method to format Duration (e.g., 00:00:05)
    private String formatTime(Duration elapsed) {
        int intElapsed = (int) Math.floor(elapsed.toSeconds());
        int hours = intElapsed / (3600);
        int minutes = (intElapsed % 3600) / 60;
        int seconds = intElapsed % 60;
        if (hours > 0) {
            return String.format("%d:%02d:%02d", hours, minutes, seconds);
        } else {
            return String.format("%02d:%02d", minutes, seconds);
        }
    }
    public static void main(String[] args) {
        launch(args);
    }
}

Step 4: Run the Application

If you're using Maven, run the following command in your project's root directory:

mvn javafx:run

If you're using Gradle:

gradle run

You should see a window appear with your video playing and the control panel at the bottom.


Handling Audio Files

Playing an audio file is almost identical. The only difference is that you don't strictly need a MediaView since there's no visual component. However, you can still use one to display album art or a static image if the media file has metadata.

Here’s a simplified version for audio:

// ... inside the start method ...
// Assume 'media' object is created as before
MediaPlayer audioPlayer = new MediaPlayer(media);
// You can still use a MediaView if you want to display something
MediaView mediaView = new MediaView(audioPlayer);
// You might set an image or a simple background for the MediaView
// mediaView.setPreserveRatio(false); // Fill the space
// Add controls as before...
// audioPlayer.play();

Key MediaPlayer Methods and Properties

Method/Property Description
play() Starts or resumes playback.
pause() Pauses playback.
stop() Stops playback and resets the currentTime to the beginning.
setVolume(double) Sets the volume, where 0 is mute and 0 is full volume.
setCycleCount(int) Sets how many times the media should play. Use MediaPlayer.INDEFINITE for looping.
setRate(double) Sets the playback rate (0 is normal, 0 is double speed).
dispose() Crucial! Releases all resources held by the player. Call this when the player is no longer needed (e.g., when the application closes).
currentTimeProperty() A property representing the current playback position.
totalDurationProperty() A property representing the total duration of the media.
statusProperty() A property representing the player's current status (READY, PLAYING, etc.).

Troubleshooting Common Issues

  • MediaPlayer error: Unrecognized format or Unrecognized container: This means the JavaFX media engine doesn't have a native codec for that file format. JavaFX has built-in support for common formats like MP3, MP4 (H.264 video + AAC audio), and WAV. For other formats, you may need to install platform-specific codec packs.
  • NoClassDefFoundError: javafx/scene/media/MediaPlayer: This means the JavaFX modules are not in your classpath. Double-check your Maven or Gradle dependencies.
  • The application runs but no sound/video: Ensure your media file is not corrupted and is in a supported format. Check the console for any error messages.
分享:
扫描分享到社交APP
上一篇
下一篇