使用Java创建视频播放器

10

我需要使用Java创建一个视频播放器来完成我的项目。我已经查看了互联网上的许多示例。其中一些可以运行,但不显示任何屏幕,我只能听到视频的声音。请帮助我解决这个问题...

我正在使用以下导入

import javax.media.*;

编辑: 以下是我使用的代码:

import java.awt.*;
 import java.awt.event.*;
 import java.io.*;
 import javax.swing.*;
 import javax.media.*;

 public class MediaPlayerDemo extends JFrame 
 {
     private Player player;
     private File file;

     public MediaPlayerDemo()
     {
         super( "Demonstrating the Java Media Player" );

         JButton openFile = new JButton( "Open file to play" );
         openFile.addActionListener( new ActionListener() 
         {
             public void actionPerformed( ActionEvent e )
             {
                 openFile();
                 createPlayer();
             }
         });
         getContentPane().add( openFile, BorderLayout.NORTH );

         setSize( 300, 300 );
         show();
     }

     private void openFile()
     {
         JFileChooser fileChooser = new JFileChooser();

         fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
         int result = fileChooser.showOpenDialog( this );

         // user clicked Cancel button on dialog
         if ( result == JFileChooser.CANCEL_OPTION )
             file = null;
         else
             file = fileChooser.getSelectedFile();
     }

     private void createPlayer()
     {
         if ( file == null )
             return;

         removePreviousPlayer();

         try 
         {
             // create a new player and add listener
             player = Manager.createPlayer( file.toURL() );
             player.addControllerListener( new EventHandler() );
             player.start(); // start player
         }
         catch ( Exception e )
         {
             JOptionPane.showMessageDialog( this, "Invalid file or location", "Error loading file",
             JOptionPane.ERROR_MESSAGE );
         }
     }

     private void removePreviousPlayer()
     {
         if ( player == null )
             return;

         player.close();

         Component visual = player.getVisualComponent();
         Component control = player.getControlPanelComponent();

         Container c = getContentPane();

         if ( visual != null )
             c.remove( visual );

         if ( control != null )
             c.remove( control );
     }

     public static void main(String args[])
     {
         MediaPlayerDemo app = new MediaPlayerDemo();

         app.addWindowListener( new WindowAdapter() 
         {
             public void windowClosing( WindowEvent e )
             {
                 System.exit(0);
             }
         });
     }

     // inner class to handler events from media player
     private class EventHandler implements ControllerListener 
     {
         public void controllerUpdate( ControllerEvent e ) 
         {
             if ( e instanceof RealizeCompleteEvent ) 
             {
                 Container c = getContentPane();

                 // load Visual and Control components if they exist
                 Component visualComponent = player.getVisualComponent();

                 if ( visualComponent != null )
                     c.add( visualComponent, BorderLayout.CENTER );

                 Component controlsComponent = player.getControlPanelComponent();

                 if ( controlsComponent != null )
                     c.add( controlsComponent, BorderLayout.SOUTH );

                 c.doLayout();
             }
         }
     }
 }

1
请分享您尝试过的代码。 - Helping Hands
你能更具体地说明在代码中哪里出现了错误吗? - Helping Hands
我可以运行代码,但不知道为什么我只能听到我选择的视频的声音,但屏幕没有显示出来。 - Anna
你可以尝试使用Java媒体框架API来更轻松地创建多媒体应用程序。请参考此链接以获取更多详细信息:http://www.javaworld.com/article/2077644/java-se/java-media-framework-player-api.html - G.Srinivas Kishan
4个回答

8
我使用了vlcj,它运行非常顺畅。这是一个Java绑定到vlcj播放器的工具,好处是你不需要提供任何驱动程序,因为vlcj已经在二进制分发中包含了所有驱动程序。
试一试吧,这里有一个已经可用的播放器示例供您使用!

假设我想分发我的播放器,如果用户在非默认位置安装了VLC库,我该如何做到这一点? - mautrok
那个在 Mac 上没用,它不起作用。 - Hasen
@Hasen 实际上,在 MacOS 上它对我来说几乎是开箱即用的。 - Petro Semeniuk
@Petro Semeniuk 它只能在 Mac 上使用 Java 1.6,这是一个严重的缺陷。作者在文档中对 Mac 上的 Java 抱怨了很多。 - Hasen

4

尝试使用JavaFX Mediaplayer:

可用的编解码器:

  • 音频:MP3;包含未压缩PCM的AIFF;包含未压缩PCM的WAV;使用高级音频编码(AAC)的MPEG-4多媒体容器
  • 视频:包含VP6视频和MP3音频的FLV; 使用H.264 / AVC(高级视频编码)视频压缩的MPEG-4多媒体容器。

这是Oracle提供的一个示例:

import javafx.application.Application;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaView;
import javafx.scene.media.Track;
import javafx.stage.Stage;

/**
 * A sample media player which loops indefinitely over the same video
 */
public class MediaPlayer extends Application {
private static final String MEDIA_URL = "http://someserver/somedir/somefile.mp4";

private static String arg1;

    @Override public void start(Stage stage) {
        stage.setTitle("Media Player");

// Create media player
        Media media = new Media((arg1 != null) ? arg1 : MEDIA_URL);
        javafx.scene.media.MediaPlayer mediaPlayer = new javafx.scene.media.MediaPlayer(media);
        mediaPlayer.setAutoPlay(true);
        mediaPlayer.setCycleCount(javafx.scene.media.MediaPlayer.INDEFINITE);

// Print track and metadata information
        media.getTracks().addListener(new ListChangeListener<Track>() {
public void onChanged(Change<? extends Track> change) {
                System.out.println("Track> "+change.getList());
            }
        });
        media.getMetadata().addListener(new MapChangeListener<String,Object>() {
public void onChanged(MapChangeListener.Change<? extends String, ? extends Object> change) {
                System.out.println("Metadata> "+change.getKey()+" -> "+change.getValueAdded());
            }
        });

// Add media display node to the scene graph
        MediaView mediaView = new MediaView(mediaPlayer);
        Group root = new Group();
        Scene scene = new Scene(root,800,600);
        root.getChildren().add(mediaView);
        stage.setScene(scene);
        stage.show();
    }

public static void main(String[] args) {
if (args.length > 0) {
            arg1 = args[0];
        }
        Application.launch(args);
    }
}

https://blogs.oracle.com/javafx/entry/mpeg_4_multimedia_support_in


Mediaplayer 虽然功能齐全,但如果您更改速度,则音调也会随之升高或降低,这通常是不可取的...而且没有任何解决方法。这是一个真正的缺点。 - Hasen

1
这是可用的代码。
package New;

import java.net.URL;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FxMediaExample2 extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {
        // Locate the media content in the CLASSPATH
        URL mediaUrl = getClass().getResource("Test.mp4");
        String mediaStringUrl = mediaUrl.toExternalForm();

        // Create a Media
        Media media = new Media(mediaStringUrl);

        // Create a Media Player
        final MediaPlayer player = new MediaPlayer(media);
        // Automatically begin the playback
        player.setAutoPlay(true);

        // Create a 400X300 MediaView
        MediaView mediaView = new MediaView(player);

        mediaView.setFitWidth(400);
        mediaView.setFitHeight(300);
        mediaView.setSmooth(true);
        mediaView.setLayoutX(200);
        mediaView.setLayoutY(200);
        // Create the DropShadow effect
        DropShadow dropshadow = new DropShadow();
        dropshadow.setOffsetY(5.0);
        dropshadow.setOffsetX(5.0);
        dropshadow.setColor(Color.RED);

        mediaView.setEffect(dropshadow);

        Rectangle rect4 = new Rectangle(35, 55, 95, 25);
        rect4.setFill(Color.RED);
        rect4.setStroke(Color.BLACK);
        rect4.setStrokeWidth(1);

        // Create the HBox
        // HBox controlBox = new HBox(5, null, null);

        // Create the VBox
        VBox root = new VBox(1, mediaView);

        GridPane gridpane = new GridPane();
        gridpane.setPadding(new Insets(95));
        gridpane.setHgap(1);
        gridpane.setVgap(10);

        GridPane.setHalignment(rect4, HPos.CENTER);

        Group grp = new Group();
        gridpane.add(root, 1, 1);

        grp.getChildren().add(gridpane);

        // Create the Scene
        Scene scene = new Scene(grp);

        // Add the scene to the Stage
        stage.setScene(scene);
        // Set the title of the Stage
        stage.setTitle("A simple Media Example");
        // Display the Stage
        stage.show();
    }
}

0

Java媒体框架可用于创建多媒体应用程序,如视频和音频播放器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接