vlcj - Guida rapida
Il vlcj è un progetto Open Source che aiuta a eseguire VLC player all'interno di un'applicazione basata su Java. Fornisce l'opzione per scoprire il lettore VLC installato nel sistema e collegarlo per creare un client di lettore multimediale e un software server utilizzando Java.
Utilizzando Java, puoi semplicemente riprodurre un file multimediale locale e persino creare un server di streaming video su richiesta.
Utilizzo
vlcj è una libreria basata su Java molto popolare ed è utilizzata in vari software basati su Java come navi di ricerca oceanografica e soluzioni IPTV e home cinema su misura. Alcuni degli esempi più famosi sono la videocamera Open Source di Elphel e il video mapping per il progetto Open Street Map.
Sintassi
Crea un componente EmbeddedMediaPlayerComponent
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
Riproduci il video
La riproduzione di un video è molto semplice. Passa il percorso del file e riprodurrà il video.
//pass path to media file
mediaPlayerComponent.mediaPlayer().media().play(path);
VLC Player
VLC Media Player è un lettore multimediale molto popolare ed è disponibile per Linux, MacOS e Windows. Viene fornito in bundle con tonnellate di codec per riprodurre qualsiasi tipo di media senza bisogno di installare un codec multimediale esterno. Supporta anche lo streaming video attraverso le reti e consente la transcodifica dei media. Usando VLC media player possiamo riprodurre file multimediali locali, flussi di rete locale, flussi video basati su Internet, DVD, Bluray, webcam, video digitali e molto altro ancora.
VLC Media Player è compilato nel codice della piattaforma nativa e non può essere utilizzato direttamente dai programmi Java. Per superare questo problema, VLC Media Player fornisce un'API (Application Programming Interface) nativa chiamata LibVLC e fa parte di VLC Media Player. vlcj fornisce quindi il livello java necessario per interagire con VLC Media Player utilizzando LibVLC.
Caratteristiche vlcj
vlcj è una libreria matura. Fornisce le seguenti funzionalità essenziali quando si lavora con VLC media player.
Java Bindings - vlcj fornisce l'associazione Java a tutte le operazioni native di VLC Media Player in modo da poter programmare una funzionalità di Media Player utilizzando la programmazione Java.
Framework - vlcj agisce come un framework che incapsula qualsiasi comportamento specifico della piattaforma e gestione del codice nativo fornendo una semplice interfaccia di programmazione di alto livello per LibVLC.
Robust- vlcj garantisce il corretto utilizzo delle API LibVLC. Poiché un uso errato può portare a crash o deadlock.
Handles Asynchronous native events- vlcj registra i callback per eventi nativi asincroni che possono essere gestiti facilmente nel pattern listener java. Questo modello di programmazione aiuta a prevenire i deadlock.
vlcj Applications
Di seguito sono riportati alcuni esempi in cui è possibile utilizzare vlcj.
Java Based - Essendo basato su java, possiamo creare lettori multimediali all'interno di programmi swing, awt, swt, javafx e openGL.
IDE - Le applicazioni Rich Client Platform basate su Eclipse / NetBeans possono utilizzare vlcj per applicazioni basate su supporti.
Internet Radio Player - Utilizzando vlcj, possiamo creare un lettore audio in grado di riprodurre in streaming radio basate su Internet.
YouTube Player - Usando vlcj, possiamo creare un lettore YouTube che può riprodurre in streaming video di YouTube.
Transcoder - Usando vlcj, possiamo transcodificare qualsiasi video.
Network streaming server - Usando vlcj, possiamo creare un server video on demand.
Network streaming client - Usando vlcj, possiamo creare un client video on demand.
Video Playing Applet - Usando vlcj, possiamo creare un'applet che può riprodurre un video.
WebCam - Usando vlcj, possiamo creare un'applicazione webcam.
CCTV Camera - Utilizzando vlcj, possiamo creare un'applicazione per telecamere CCTV che riproduce video registrati da telecamere CCTV.
Licenza
vlcj è distribuibile con i termini di licenza GPL . In caso di utilizzo commerciale senza condizioni di licenza GPL, contattare il team di Caprica Software Limited .
vlcj è una libreria basata su Java, quindi il primo requisito è avere JDK installato sulla tua macchina.
Passaggio 1: configurazione del Java Development Kit (JDK)
È possibile scaricare l'ultima versione di SDK dal sito Java di Oracle - Download di Java SE. Troverai le istruzioni per l'installazione di JDK nei file scaricati, segui le istruzioni fornite per installare e configurare il setup. Infine, impostare le variabili di ambiente PATH e JAVA_HOME in modo che facciano riferimento alla directory che contiene java e javac, tipicamente java_install_dir / bin e java_install_dir rispettivamente.
Se stai usando Windows e hai installato JDK in C: \ jdk1.6.0_15, dovresti inserire la seguente riga nel tuo file C: \ autoexec.bat.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
In alternativa, su Windows NT / 2000 / XP, dovrai fare clic con il pulsante destro del mouse su Risorse del computer, selezionare Proprietà → Avanzate → Variabili d'ambiente. Quindi, dovrai aggiornare il valore PATH e fare clic sul pulsante OK.
Su Unix (Solaris, Linux, ecc.), Se l'SDK è installato in /usr/local/jdk1.6.0_15 e utilizzi la shell C, dovrai inserire quanto segue nel tuo file .cshrc.
setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_15
In alternativa, se utilizzi un IDE (Integrated Development Environment) come Borland JBuilder, Eclipse, IntelliJ IDEA o Sun ONE Studio, dovrai compilare ed eseguire un semplice programma per confermare che l'IDE sa dove hai installato Java. Altrimenti, dovrai eseguire una corretta configurazione come indicato nel documento dell'IDE.
Passaggio 2: installare la libreria vlcj insieme alle dipendenze
Scarica i seguenti jar da MVNRepository e usali nel tuo classpath.
- vlc-4.4.4.jar
- vlc-natives-4.1.0.jar
- jna-5.2.0.jar
- jna-platform-5.2.0.jar
Assicurati di impostare correttamente la tua variabile CLASSPATH su questa directory altrimenti dovrai affrontare un problema durante l'esecuzione dell'applicazione.
Passaggio 3: configurazione dell'IDE di Eclipse
Tutti gli esempi in questo tutorial sono stati scritti utilizzando Eclipse IDE. Quindi ti suggeriamo di avere l'ultima versione di Eclipse installata sulla tua macchina.
Per installare Eclipse IDE, scarica gli ultimi binari Eclipse da https://www.eclipse.org/downloads/. Dopo aver scaricato l'installazione, decomprimere la distribuzione binaria in una posizione comoda. Ad esempio, in C: \ eclipse su Windows o / usr / local / eclipse su Linux / Unix e infine impostare la variabile PATH in modo appropriato.
Eclipse può essere avviato eseguendo i seguenti comandi sulla macchina Windows, oppure puoi semplicemente fare doppio clic su eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse può essere avviato eseguendo i seguenti comandi su una macchina Unix (Solaris, Linux, ecc.) -
$/usr/local/eclipse/eclipse
Passaggio 4: creare un progetto Maven
C:\MVN>mvn archetype:generate
-DgroupId = com.tutorialspoint.media
-DartifactId = mediaPlayer
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false
Creerà un progetto esperto. Ora aggiorna il file pom.xml come segue:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.media</groupId>
<artifactId>mediaPlayer</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>mediaPlayer</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>uk.co.caprica</groupId>
<artifactId>vlcj</artifactId>
<version>4.4.4</version>
</dependency>
</dependencies>
</project>
Esegui il comando seguente per aggiornare le dipendenze di Maven e creare il progetto.
mvn package
Una volta che il comando è riuscito. Importa il progetto di lettore multimediale basato su Maven in Eclipse come progetto Maven. Rest Eclipse gestirà.
Passaggio 5: installa VLC Player
Scarica l'ultima versione di VLC Player dalla loro home page VLC media player e installala utilizzando il loro programma di installazione. La libreria vlcj 4.4 richiede VLC 3.0 in poi e Java 8 come prerequisiti.
VLC Player Discovery
La libreria vlcj fornisce una classe che esegue il rilevamento automatico del lettore VLC installato nel sistema utilizzando la seguente sintassi.
EmbeddedMediaPlayerComponent mediaPlayerComponent = = new EmbeddedMediaPlayerComponent();
Carica video
Ora usando i media possiamo facilmente caricare un video nella nostra applicazione usando la seguente sintassi:
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
Riproduci video
Ora usando i controlli possiamo facilmente riprodurre un video nella nostra applicazione usando la seguente sintassi:
mediaPlayerComponent.mediaPlayer().controls().play();
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Fare clic sul pulsante Riproduci e il video inizierà a essere riprodotto.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo il capitolo Play Video di vlcj con funzionalità di pausa video.
Metti in pausa il video
Ora usando i controlli possiamo facilmente mettere in pausa un video nella nostra applicazione usando la seguente sintassi:
mediaPlayerComponent.mediaPlayer().controls().pause();
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Fare clic sul pulsante Riproduci e il video inizierà a essere riprodotto, quindi fare clic sul pulsante di pausa. Ora il video verrà messo in pausa.
Esempio
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora puoi riprodurre, mettere in pausa e riavvolgere un video.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo il capitolo vlcj Pause Video con funzionalità Seek video.
Cerca video
Ora utilizzando i controlli possiamo facilmente riavvolgere un video nella nostra applicazione utilizzando la seguente sintassi:
mediaPlayerComponent.mediaPlayer().controls().skipWhile(10000);
Qui stiamo passando un valore positivo (la lunghezza da in avanti) per riavvolgere il video.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora puoi riprodurre, mettere in pausa, riavvolgere e saltare un video.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo il capitolo Seek Video di vlcj con la gestione della capacità di riproduzione degli eventi.
Gestione degli eventi di gioco
Aggiungi il gestore di eventi in riproduzione utilizzando la seguente sintassi (metodo modello):
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void playing(MediaPlayer mediaPlayer) {
}
};
Oppure possiamo aggiungere il gestore di eventi di riproduzione utilizzando la seguente sintassi (metodo Listener):
mediaPlayerComponent.getMediaPlayer().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void playing(MediaPlayer mediaPlayer) {
}
});
Quando viene riprodotto un video, viene generato un evento di riproduzione.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
};
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora puoi vedere nel registro della console che quando il video viene caricato mostra un messaggio come segue:
Media Playback started.
Ora fai clic su vari pulsanti. Dopo aver fatto clic sul pulsante di riproduzione, nella console verrà visualizzato il messaggio sopra.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Riproduzione di eventi video con la gestione della capacità dell'evento finito.
Gestione evento terminato
Aggiungi il gestore di eventi finito utilizzando la seguente sintassi (metodo modello) -
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void finished(MediaPlayer mediaPlayer) {
}
};
Oppure possiamo aggiungere un gestore di eventi finito usando la seguente sintassi (metodo Listener) -
mediaPlayerComponent.getMediaPlayer().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
}
});
Quando un video viene riprodotto completamente, viene generato l'evento finito.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
};
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora riproduci il video e attendi che sia finito, quindi viene visualizzato un messaggio come segue -
Media Playback finished.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Evento video finito con capacità di gestione degli errori.
Gestione degli eventi di errore
Aggiungi il gestore degli eventi di errore utilizzando la seguente sintassi (metodo modello):
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void error(MediaPlayer mediaPlayer) {
}
};
Oppure possiamo aggiungere un gestore di eventi di errore utilizzando la seguente sintassi (metodo Listener):
mediaPlayerComponent.getMediaPlayer().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void error(MediaPlayer mediaPlayer) {
}
});
Quando un video non viene caricato, viene generato un evento di errore. Ma quando il metodo di riproduzione ritorna immediatamente e l'evento di errore verrà generato (nel caso in cui il video venga caricato e non venga eseguito) in seguito. Quindi dobbiamo gestire gli eventi di errore in modo asincrono.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Qui viene fornito un percorso non valido per il file multimediale. Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora vedrà un messaggio nella console come segue -
Failed to load Media.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Errore durante il caricamento del capitolo Evento video con capacità di gestione degli eventi del mouse.
Gestione degli eventi del mouse
Aggiungi gestori di eventi del mouse utilizzando la seguente sintassi (metodo modello):
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
};
Oppure possiamo aggiungere il gestore di eventi del mouse usando la seguente sintassi (metodo Listener):
Component videoSurface = mediaPlayerComponent.videoSurfaceComponent();
videoSurface.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
});
videoSurface.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
});
In caso di metodo Listener su Windows, è necessario disabilitare la gestione dell'input del mouse nativo utilizzando la seguente sintassi.
mediaPlayerComponent.mediaPlayer().input().enableMouseInputHandling(false);
Quando usiamo il mouse all'interno di una superficie video, verrà generato l'evento mouse.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora fai clic all'interno del video e vedrai un messaggio nella console come segue -
Media Playback started.
Media Playback started.
Mouse Clicked. (377,180)
Mouse Clicked. (377,180)
Mouse Clicked. (356,120)
Media Playback finished.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo il capitolo vlcj - Gestione degli eventi del mouse con funzionalità di gestione degli eventi della tastiera.
Gestione degli eventi della tastiera
Aggiungi gestori di eventi del mouse utilizzando la seguente sintassi (metodo modello):
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void keyPressed(KeyEvent e) {
}
};
Oppure possiamo aggiungere il gestore di eventi della tastiera usando la seguente sintassi (metodo Listener) -
Component videoSurface = mediaPlayerComponent.videoSurfaceComponent();
videoSurface.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
}
});
In caso di metodo Listener su Windows, è necessario disabilitare la gestione dell'input da tastiera nativa utilizzando la seguente sintassi.
mediaPlayerComponent.mediaPlayer().input().enableKeyInputHandling(false);
Quando premiamo un tasto qualsiasi, verrà generato l'evento della tastiera.
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
JPanel controlsPane = new JPanel();
playButton = new JButton("Play");
controlsPane.add(playButton);
pauseButton = new JButton("Pause");
controlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
controlsPane.add(rewindButton);
skipButton = new JButton("Skip");
controlsPane.add(skipButton);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora premi un tasto qualsiasi e vedrai i messaggi nella console come segue:
Media Playback started.
Media Playback started.
Mouse Clicked. (345,231)
Key pressed. 82
Media Playback finished.
Key pressed. 82
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Gestione eventi tastiera con funzionalità di riproduzione audio. Simile alla riproduzione video, possiamo controllare anche una riproduzione audio in modo semplice.
Crea un lettore audio
AudioPlayerComponent audioPlayerComponent = new AudioPlayerComponent();
Carica audio
Ora usando i media possiamo facilmente caricare un audio nella nostra applicazione usando la seguente sintassi:
audioPlayerComponent.mediaPlayer().media().startPaused(path);
Riproduci audio
Ora utilizzando i controlli possiamo riprodurre facilmente una clip audio nella nostra applicazione utilizzando la seguente sintassi:
audioPlayerComponent.mediaPlayer().controls().play();
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora premi il pulsante di riproduzione nei controlli audio e inizierà la riproduzione di una clip. Fare clic sul pulsante di pausa metterà in pausa l'audio.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Audio Player con supporto Marquee. Possiamo aggiungere un testo come una sovrapposizione sul video.
Crea e costruisci un tendone
Marquee marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
Imposta Marquee
Ora utilizzando il metodo marquee possiamo facilmente impostare un marquee sul nostro video nella nostra applicazione utilizzando la seguente sintassi:
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Marquee con il supporto del logo. Possiamo aggiungere un testo come una sovrapposizione sul video.
Crea e costruisci un logo
Logo logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
Imposta il logo
Ora usando il metodo logo possiamo facilmente impostare un logo sul nostro video nella nostra applicazione usando la seguente sintassi-
mediaPlayerComponent.mediaPlayer().logo().set(logo);
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.player.base.Logo;
import uk.co.caprica.vlcj.player.base.LogoPosition;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private static final String LOGO_PATH = "D:\\Downloads\\logo.png";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private final Logo logo;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
mediaPlayerComponent.mediaPlayer().logo().set(logo);
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Logo con supporto per le informazioni sui media.
Analizza i media utilizzando mediaPlayer
mediaPlayerComponent.mediaPlayer().media().parsing().parse();
Gestisci evento di analisi
mediaPlayerComponent.mediaPlayer().events().addMediaEventListener(new MediaEventAdapter() {
@Override
public void mediaParsedChanged(Media media, MediaParsedStatus newStatus) {
}
}
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.media.Media;
import uk.co.caprica.vlcj.media.MediaEventAdapter;
import uk.co.caprica.vlcj.media.MediaParsedStatus;
import uk.co.caprica.vlcj.media.TrackInfo;
import uk.co.caprica.vlcj.player.base.ChapterDescription;
import uk.co.caprica.vlcj.player.base.Logo;
import uk.co.caprica.vlcj.player.base.LogoPosition;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.base.TitleDescription;
import uk.co.caprica.vlcj.player.base.TrackDescription;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private static final String LOGO_PATH = "D:\\Downloads\\logo.png";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private final Logo logo;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
mediaPlayerComponent.mediaPlayer().logo().set(logo);
mediaPlayerComponent.mediaPlayer().events().addMediaEventListener(new MediaEventAdapter() {
@Override
public void mediaParsedChanged(Media media,
MediaParsedStatus newStatus) {
if(newStatus == MediaParsedStatus.DONE) {
MediaPlayer mediaPlayer = mediaPlayerComponent.mediaPlayer();
List<TrackDescription> videoTracks = mediaPlayer.video().trackDescriptions();
System.out.println(videoTracks.get(1));
List<TitleDescription> titles = mediaPlayer.titles().titleDescriptions();
if(!titles.isEmpty()) {
System.out.println(titles.get(0));
}
List<ChapterDescription> chapters = mediaPlayer.chapters().descriptions();
if(!chapters.isEmpty()) {
System.out.println(chapters.get(0));
}
List<? extends TrackInfo> trackInfo = mediaPlayer.media().info().tracks();
if(!trackInfo.isEmpty()) {
System.out.println(trackInfo.get(0));
}
}
}
});
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
mediaPlayerComponent.mediaPlayer().media().parsing().parse();
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
E mostrerà i messaggi come segue -
TrackDescription[id=0,description=Track 1]
VideoTrackInfo[codec=0x34363268,codecName=h264,originalCodec=0x31637661,
originalCodecName=avc1,id=0,profile=-1,level=-1,bitRate=0,language=null,
description=null,codecDescription=H264 - MPEG-4 AVC (part 10)]
[width=596,height=336,sampleAspectRatio=1,sampleAspectRatioBase=1,
frameRate=30000,frameRateBase=1001,orientation=TOP_LEFT,projection=RECTANGULAR,
yaw=0.0,pitch=0.0,roll=0.0,fov=80.0,multiview=null]
Media Playback started.
TrackDescription[id=0,description=Track 1]
VideoTrackInfo[codec=0x34363268,codecName=h264,originalCodec=0x31637661,
originalCodecName=avc1,id=0,profile=-1,level=-1,bitRate=0,language=null,
description=null,codecDescription=H264 - MPEG-4 AVC (part 10)]
[width=596,height=336,sampleAspectRatio=1,sampleAspectRatioBase=1,
frameRate=30000,frameRateBase=1001,orientation=TOP_LEFT,projection=RECTANGULAR,
yaw=0.0,pitch=0.0,roll=0.0,fov=80.0,multiview=null]
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Informazioni multimediali con supporto per la riproduzione a schermo intero.
Allega una strategia a schermo intero
Stiamo usando AdaptiveFullScreenStrategy che utilizza internamente XFullScreenStrategy, una strategia nativa a schermo intero per Linux e Win32FullScreenStrategy, una strategia nativa a schermo intero per Windows.
mediaPlayerComponent.mediaPlayer().fullScreen().strategy(
new AdaptiveFullScreenStrategy(this));
Attiva la modalità a schermo intero
Il codice seguente alterna la modalità a schermo intero.
mediaPlayerComponent.mediaPlayer().fullScreen().toggle();
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.media.Media;
import uk.co.caprica.vlcj.media.MediaEventAdapter;
import uk.co.caprica.vlcj.media.MediaParsedStatus;
import uk.co.caprica.vlcj.media.TrackInfo;
import uk.co.caprica.vlcj.player.base.ChapterDescription;
import uk.co.caprica.vlcj.player.base.Logo;
import uk.co.caprica.vlcj.player.base.LogoPosition;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.base.TitleDescription;
import uk.co.caprica.vlcj.player.base.TrackDescription;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.fullscreen.adaptive.AdaptiveFullScreenStrategy;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private static final String LOGO_PATH = "D:\\Downloads\\logo.png";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private final Logo logo;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
private JToggleButton toggleButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
mediaPlayerComponent.mediaPlayer().logo().set(logo);
mediaPlayerComponent.mediaPlayer().events().addMediaEventListener(new MediaEventAdapter() {
@Override
public void mediaParsedChanged(Media media,
MediaParsedStatus newStatus) {
if(newStatus == MediaParsedStatus.DONE) {
MediaPlayer mediaPlayer = mediaPlayerComponent.mediaPlayer();
List<TrackDescription> videoTracks = mediaPlayer.video().trackDescriptions();
System.out.println(videoTracks.get(1));
List<TitleDescription> titles = mediaPlayer.titles().titleDescriptions();
if(!titles.isEmpty()) {
System.out.println(titles.get(0));
}
List<ChapterDescription> chapters = mediaPlayer.chapters().descriptions();
if(!chapters.isEmpty()) {
System.out.println(chapters.get(0));
}
List<? extends TrackInfo> trackInfo = mediaPlayer.media().info().tracks();
if(!trackInfo.isEmpty()) {
System.out.println(trackInfo.get(0));
}
}
}
});
mediaPlayerComponent.mediaPlayer().fullScreen().strategy(new AdaptiveFullScreenStrategy(this));
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
//Create others border
Border othersBorder = BorderFactory.createTitledBorder("Others");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel othersPane = new JPanel();
othersPane.setBorder(othersBorder);
toggleButton = new JToggleButton("Toggle Full Screen");
othersPane.add(toggleButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
controlsPane.add(othersPane);
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().fullScreen().toggle();
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
mediaPlayerComponent.mediaPlayer().media().parsing().parse();
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora fai clic sul pulsante Schermo intero e guarda il video a schermo intero.
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Video a schermo intero con un supporto per l'equalizzatore audio.
Crea un equalizzatore audio
Possiamo creare un equalizzatore con tutti i valori come zero utilizzando l'istanza di MediaPlayerFactory.
Equalizer equalizer = mediaPlayerComponent.mediaPlayerFactory().equalizer().newEqualizer();
Ottieni valori di equalizzazione preimpostati
Il codice seguente ottiene i nomi degli equalizzatori preimpostati, ad esempio Flat, Classical, Club, Dance, Headphones, ecc.
List<String> presetNames = factory.equalizer().presets();
Usa l'equalizzatore preimpostato.
Equalizer equalizer = mediaPlayerComponent.mediaPlayerFactory().equalizer().newEqualizer(presetName);
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import uk.co.caprica.vlcj.media.Media;
import uk.co.caprica.vlcj.media.MediaEventAdapter;
import uk.co.caprica.vlcj.media.MediaParsedStatus;
import uk.co.caprica.vlcj.media.TrackInfo;
import uk.co.caprica.vlcj.player.base.ChapterDescription;
import uk.co.caprica.vlcj.player.base.Equalizer;
import uk.co.caprica.vlcj.player.base.Logo;
import uk.co.caprica.vlcj.player.base.LogoPosition;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.base.TitleDescription;
import uk.co.caprica.vlcj.player.base.TrackDescription;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.fullscreen.adaptive.AdaptiveFullScreenStrategy;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private static final String LOGO_PATH = "D:\\Downloads\\logo.png";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private final Logo logo;
private final Equalizer equalizer;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
private JToggleButton toggleButton;
private JButton equalizerButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
mediaPlayerComponent.mediaPlayer().logo().set(logo);
mediaPlayerComponent.mediaPlayer().events().addMediaEventListener(new MediaEventAdapter() {
@Override
public void mediaParsedChanged(Media media,
MediaParsedStatus newStatus) {
if(newStatus == MediaParsedStatus.DONE) {
MediaPlayer mediaPlayer = mediaPlayerComponent.mediaPlayer();
List<TrackDescription> videoTracks = mediaPlayer.video().trackDescriptions();
System.out.println(videoTracks.get(1));
List<TitleDescription> titles = mediaPlayer.titles().titleDescriptions();
if(!titles.isEmpty()) {
System.out.println(titles.get(0));
}
List<ChapterDescription> chapters = mediaPlayer.chapters().descriptions();
if(!chapters.isEmpty()) {
System.out.println(chapters.get(0));
}
List<? extends TrackInfo> trackInfo = mediaPlayer.media().info().tracks();
if(!trackInfo.isEmpty()) {
System.out.println(trackInfo.get(0));
}
}
}
});
mediaPlayerComponent.mediaPlayer().fullScreen().strategy(new AdaptiveFullScreenStrategy(this));
List<String> presetNames = mediaPlayerComponent.mediaPlayerFactory().equalizer().presets();
System.out.println(presetNames);
equalizer = mediaPlayerComponent.mediaPlayerFactory().equalizer().newEqualizer("Dance");
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
//Create others border
Border othersBorder = BorderFactory.createTitledBorder("Others");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel othersPane = new JPanel();
othersPane.setBorder(othersBorder);
toggleButton = new JToggleButton("Toggle Full Screen");
equalizerButton = new JButton("Equalizer");
othersPane.add(toggleButton);
othersPane.add(equalizerButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
controlsPane.add(othersPane);
controlsPane.setPreferredSize(new Dimension(400, 120));
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().fullScreen().toggle();
}
});
equalizerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().audio().setEqualizer(equalizer);
System.out.println("Using equalizer: " + equalizer);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
mediaPlayerComponent.mediaPlayer().media().parsing().parse();
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora fai clic sul pulsante dell'equalizzatore e guarda i dettagli dell'equalizzatore nella console come segue.
[Flat, Classical, Club, Dance, Full bass, Full bass and treble,
Full treble, Headphones, Large Hall, Live, Party, Pop, Reggae,
Rock, Ska, Soft, Soft rock, Techno]
TrackDescription[id=0,description=Track 1]
VideoTrackInfo[codec=0x34363268,codecName=h264,originalCodec=0x31637661,
originalCodecName=avc1,id=0,profile=-1,level=-1,bitRate=0,language=null,
description=null,codecDescription=H264 - MPEG-4 AVC (part 10)]
[width=596,height=336,sampleAspectRatio=1,sampleAspectRatioBase=1,
frameRate=30000,frameRateBase=1001,orientation=TOP_LEFT,
projection=RECTANGULAR,yaw=0.0,pitch=0.0,roll=0.0,fov=80.0,multiview=null]
Media Playback started.
TrackDescription[id=0,description=Track 1]
VideoTrackInfo[codec=0x34363268,codecName=h264,originalCodec=0x31637661,
originalCodecName=avc1,id=0,profile=-1,level=-1,bitRate=0,language=null,
description=null,codecDescription=H264 - MPEG-4 AVC (part 10)]
[width=596,height=336,sampleAspectRatio=1,sampleAspectRatioBase=1,
frameRate=30000,frameRateBase=1001,orientation=TOP_LEFT,projection=RECTANGULAR,
yaw=0.0,pitch=0.0,roll=0.0,fov=80.0,multiview=null]
Using equalizer: Equalizer[preamp=5.0,bandAmps=[9.6, 7.2, 2.4,
-1.11022E-15, -1.11022E-15, -5.6, -7.2, -7.2, -1.11022E-15, -1.11022E-15]]
Miglioriamo ulteriormente l'applicazione in cui aggiorneremo vlcj - Capitolo Audio Equalizer con un supporto di sovrapposizione.
Crea una sovrapposizione
Possiamo creare una sovrapposizione come una finestra oscillante da mostrare su un video.
class Overlay extends Window {
public Overlay(Window owner) {
super(owner, WindowUtils.getAlphaCompatibleGraphicsConfiguration());
setBackground(new Color(0, 0, 0, 0));
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
}
Crea e imposta overlay
Il codice seguente imposta l'overlay per il supporto.
Overlay overlay = new Overlay(this);
mediaPlayerComponent.mediaPlayer().overlay().set(overlay);
Abilita / Disabilita Overlay su richiesta.
mediaPlayerComponent.mediaPlayer().overlay().enable(overlayEnabled);
Esempio
Apri il progetto mediaPlayer come creato nel capitolo Configurazione dell'ambiente in Eclipse.
Aggiorna App.java con il seguente codice−
App.java
package com.tutorialspoint.media;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import com.sun.jna.platform.WindowUtils;
import uk.co.caprica.vlcj.media.Media;
import uk.co.caprica.vlcj.media.MediaEventAdapter;
import uk.co.caprica.vlcj.media.MediaParsedStatus;
import uk.co.caprica.vlcj.media.TrackInfo;
import uk.co.caprica.vlcj.player.base.ChapterDescription;
import uk.co.caprica.vlcj.player.base.Equalizer;
import uk.co.caprica.vlcj.player.base.Logo;
import uk.co.caprica.vlcj.player.base.LogoPosition;
import uk.co.caprica.vlcj.player.base.Marquee;
import uk.co.caprica.vlcj.player.base.MarqueePosition;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter;
import uk.co.caprica.vlcj.player.base.TitleDescription;
import uk.co.caprica.vlcj.player.base.TrackDescription;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.embedded.fullscreen.adaptive.AdaptiveFullScreenStrategy;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private static final String TITLE = "My First Media Player";
private static final String VIDEO_PATH = "D:\\Downloads\\sunset-beach.mp4";
private static final String AUDIO_PATH = "D:\\Downloads\\time-to-feel-good.mp3";
private static final String LOGO_PATH = "D:\\Downloads\\logo.png";
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private final AudioPlayerComponent audioPlayerComponent;
private final Marquee marquee;
private final Logo logo;
private final Equalizer equalizer;
private final Overlay overlay;
private boolean overlayEnabled = false;
private JButton playButton;
private JButton pauseButton;
private JButton rewindButton;
private JButton skipButton;
private JButton playAudioButton;
private JButton pauseAudioButton;
private JToggleButton toggleButton;
private JButton equalizerButton;
private JToggleButton overlayButton;
public App(String title) {
super(title);
mediaPlayerComponent = new EmbeddedMediaPlayerComponent() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("Mouse Clicked. (" + e.getX() + "," + e.getY() + ")");
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
super.mouseWheelMoved(e);
System.out.println("Mouse wheel moved. " + e.getScrollAmount());
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("Key pressed. " + e.getKeyCode());
}
@Override
public void playing(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback started.");
}
@Override
public void finished(MediaPlayer mediaPlayer) {
super.playing(mediaPlayer);
System.out.println("Media Playback finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Failed to load Media.");
}
});
}
};
audioPlayerComponent = new AudioPlayerComponent();
audioPlayerComponent.mediaPlayer().events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
@Override
public void finished(MediaPlayer mediaPlayer) {
System.out.println("Audio Playback Finished.");
}
@Override
public void error(MediaPlayer mediaPlayer) {
System.out.println("Failed to load Audio.");
}
});
marquee = Marquee.marquee()
.text("TutorialsPoint")
.size(40)
.colour(Color.WHITE)
.position(MarqueePosition.BOTTOM_RIGHT)
.opacity(0.5f)
.enable();
mediaPlayerComponent.mediaPlayer().marquee().set(marquee);
logo = Logo.logo()
.file(LOGO_PATH)
.position(LogoPosition.TOP_LEFT)
.opacity(0.3f)
.enable();
mediaPlayerComponent.mediaPlayer().logo().set(logo);
mediaPlayerComponent.mediaPlayer().events().addMediaEventListener(new MediaEventAdapter() {
@Override
public void mediaParsedChanged(Media media,
MediaParsedStatus newStatus) {
if(newStatus == MediaParsedStatus.DONE) {
MediaPlayer mediaPlayer = mediaPlayerComponent.mediaPlayer();
List<TrackDescription> videoTracks = mediaPlayer.video().trackDescriptions();
System.out.println(videoTracks.get(1));
List<TitleDescription> titles = mediaPlayer.titles().titleDescriptions();
if(!titles.isEmpty()) {
System.out.println(titles.get(0));
}
List<ChapterDescription> chapters = mediaPlayer.chapters().descriptions();
if(!chapters.isEmpty()) {
System.out.println(chapters.get(0));
}
List<? extends TrackInfo> trackInfo = mediaPlayer.media().info().tracks();
if(!trackInfo.isEmpty()) {
System.out.println(trackInfo.get(0));
}
}
}
});
mediaPlayerComponent.mediaPlayer().fullScreen().strategy(new AdaptiveFullScreenStrategy(this));
List<String> presetNames = mediaPlayerComponent.mediaPlayerFactory().equalizer().presets();
System.out.println(presetNames);
equalizer = mediaPlayerComponent.mediaPlayerFactory().equalizer().newEqualizer("Dance");
overlay = new Overlay(this);
mediaPlayerComponent.mediaPlayer().overlay().set(overlay);
}
public void initialize() {
this.setBounds(100, 100, 600, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
//Create a video border
Border videoBorder = BorderFactory.createTitledBorder("Video Controls");
//Create an audio border
Border audioBorder = BorderFactory.createTitledBorder("Audio Controls");
//Create others border
Border othersBorder = BorderFactory.createTitledBorder("Others");
JPanel videoControlsPane = new JPanel();
videoControlsPane.setBorder(videoBorder);
playButton = new JButton("Play");
videoControlsPane.add(playButton);
pauseButton = new JButton("Pause");
videoControlsPane.add(pauseButton);
rewindButton = new JButton("Rewind");
videoControlsPane.add(rewindButton);
skipButton = new JButton("Skip");
videoControlsPane.add(skipButton);
JPanel audioControlsPane = new JPanel();
audioControlsPane.setBorder(audioBorder);
playAudioButton = new JButton("Play");
audioControlsPane.add(playAudioButton);
pauseAudioButton = new JButton("Pause");
audioControlsPane.add(pauseAudioButton);
JPanel othersPane = new JPanel();
othersPane.setBorder(othersBorder);
toggleButton = new JToggleButton("Toggle Full Screen");
equalizerButton = new JButton("Equalizer");
overlayButton = new JToggleButton("Toggle Overlay");
othersPane.add(toggleButton);
othersPane.add(equalizerButton);
othersPane.add(overlayButton);
JPanel controlsPane = new JPanel();
controlsPane.add(videoControlsPane);
controlsPane.add(audioControlsPane);
controlsPane.add(othersPane);
controlsPane.setPreferredSize(new Dimension(400, 120));
contentPane.add(controlsPane, BorderLayout.SOUTH);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().play();
}
});
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().pause();
}
});
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(-14000);
}
});
skipButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().controls().skipTime(4000);
}
});
playAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().play();
}
});
pauseAudioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
audioPlayerComponent.mediaPlayer().controls().pause();
}
});
toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().fullScreen().toggle();
}
});
equalizerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.mediaPlayer().audio().setEqualizer(equalizer);
System.out.println("Using equalizer: " + equalizer);
}
});
overlayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overlayEnabled = !overlayEnabled;
mediaPlayerComponent.mediaPlayer().overlay().enable(overlayEnabled);
}
});
this.setContentPane(contentPane);
this.setVisible(true);
}
public void loadVideo(String path) {
mediaPlayerComponent.mediaPlayer().media().startPaused(path);
mediaPlayerComponent.mediaPlayer().media().parsing().parse();
}
public void loadAudio(String path) {
audioPlayerComponent.mediaPlayer().media().startPaused(path);
}
public static void main( String[] args ){
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.out.println(e);
}
App application = new App(TITLE);
application.initialize();
application.setVisible(true);
application.loadVideo(VIDEO_PATH);
application.loadAudio(AUDIO_PATH);
}
}
class Overlay extends Window {
public Overlay(Window owner) {
super(owner, WindowUtils.getAlphaCompatibleGraphicsConfiguration());
setBackground(new Color(0, 0, 0, 0));
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint gp = new GradientPaint(
180.0f, 280.0f,
new Color(255, 255, 255, 255),
250.0f,
380.0f,
new Color(255, 255, 0, 0)
);
g2.setPaint(gp);
g2.setFont(new Font("Serif", Font.PLAIN,32));
g2.drawString("TutorialsPoint",200, 200);
}
}
Eseguire l'applicazione facendo clic con il pulsante destro del mouse sul file e scegliere Esegui come applicazione Java. Dopo un avvio riuscito, se tutto va bene, dovrebbe visualizzare il seguente risultato:
Ora fai clic sul pulsante Attiva / disattiva overlay e guarda il testo in sovrimpressione sul video come segue.