Problema applet com JMF

8 respostas
M

Pessoal,

Seguinte, to tentando utilizar um applet com JMF para realizar a visualização de trechos de vídeos. Estou criando o player, vide código abaixo, com o createRealizedPlayer porém o vídeo não é exibido e não é apresentada nenhuma msg de erro no console do Java. Se eu utilizar o createPlayer o vídeo é exibido normalmente, porém não posso utilizar o createPlayer pq não posso utilizar o setMediaTime pois ele diz que o player nao é Realized. Alguem tem alguma ideia do que seja ?

[]'s

player = Manager.createRealizedPlayer(mrl);

LOG CONSOLE JAVA
basic: Referencing classloader: sun.plugin.ClassLoaderInfo@6e1408, refcount=1
basic: Added progress listener: sun.plugin.util.GrayBoxPainter@5483cd
basic: Loading applet …
basic: Initializing applet …
basic: Starting applet …
basic: completed perf rollup
Applet.init() is called
Unable to handle format: mpeglayer3, 22050.0 Hz, 0-bit, Mono, Unsigned, 8000.0 frame rate, FrameSize=4608 bits
Applet.start() foi chamada
UnrealizedEstado= 100
RealizedEstado= 300
StartedEstado= 600
EstadoAtual= 400
IF do start
Entrou aqui EndOfMediaEvent
EstadoAtual= 500
Setando o tempo de inicio


CLASSE:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.lang.String;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.*;
//import com.sun.media.util.JMFSecurity;


public class PlayerAppletLobao extends Applet implements ControllerListener {
    
    // media Player
    Player player = null;
    // component in which video is playing
    Component visualComponent = null;
    // controls gain, position, start, stop
    Component controlComponent = null;
    // displays progress during download
    Component progressBar = null;
    boolean firstTime = true;
    long CachingSize = 0L;    
    Panel panel = null;
    int controlPanelHeight = 0;
    int videoWidth = 0;
    int videoHeight = 0;

    /**
     * Read the applet file parameter and create the media 
     * player.
     */
    public void init() {
	System.out.println("Applet.init() is called");
	//System.out.print("Entrou no init");
        setLayout(null);
	setBackground(Color.white);
	panel = new Panel();
	panel.setLayout( null );
	add(panel);
	panel.setBounds(0, 0, 320, 240);

	// input file name from html param
	String mediaFile = null;
	// URL for our media file
	MediaLocator mrl = null;
	URL url = null;

	// Get the media filename info.
	// The applet tag should contain the path to the
 	// source media file, relative to the html page.
	
	if ((mediaFile = getParameter("FILE")) == null)
	    Fatal("Invalid media file parameter");

	try {
	    url = new URL(getDocumentBase(), mediaFile);
	    mediaFile = url.toExternalForm();
	} catch (MalformedURLException mue) {
	}
	
	try {
	    // Create a media locator from the file name
	    if ((mrl = new MediaLocator(mediaFile)) == null)
		Fatal("Can't build URL for " + mediaFile);

	    /*
	    try {
		JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
						   JMFSecurity.writePropArgs);
		JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
						   JMFSecurity.readPropArgs);
		JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
						   JMFSecurity.connectArgs);
	    } catch (Exception e) {}
	    */
	    
	    // Create an instance of a player for this media
	    try {
                player = Manager.createRealizedPlayer(mrl);                        
		//player = Manager.createPlayer(mrl);
	    } catch (CannotRealizeException ex) {
		System.out.println(ex);
		Fatal("Could not create player for " + mrl);
            } catch (NoPlayerException e) {
		System.out.println(e);
		Fatal("Could not create player for " + mrl);
	    }

	    // Add ourselves as a listener for a player's events
	    player.addControllerListener(this);
            player.start();
	} catch (MalformedURLException e) {
	    Fatal("Invalid media file URL!");
	} catch (IOException e) {
	    Fatal("IO exception creating player for " + mrl);
	}

	// This applet assumes that its start() calls 
	// player.start(). This causes the player to become
	// realized. Once realized, the applet will get
	// the visual and control panel components and add
	// them to the Applet. These components are not added
	// during init() because they are long operations that
	// would make us appear unresposive to the user.
    }

    /**
     * Start media file playback. This function is called the
     * first time that the Applet runs and every
     * time the user re-enters the page.
     */

    public void start() {
	System.out.println("Applet.start() foi chamada");
	System.out.println("UnrealizedEstado= "+player.Unrealized);
	System.out.println("RealizedEstado= "+player.Realized);
	System.out.println("StartedEstado= "+player.Started);        
	System.out.println("EstadoAtual= "+player.getState());        
        // Call start() to prefetch and start the player.
        if (player != null){
            System.out.println("IF do start");
            //player.stop();            
            player.start();
            //player.setMediaTime(new Time(106));
            //player.setStopTime(new Time(112));
        }
       
    }

    /**
     * Stop media file playback and release resource before
     * leaving the page.
     */
    public void stop() {
	System.out.println("Applet.stop() foi chamado");
        if (player != null) {
            player.stop();
            player.setMediaTime(new Time(106));
            player.setStopTime(new Time(112));
            player.deallocate();
        }
    }

    public void destroy() {
	//$ System.out.println("Applet.destroy() is called");
	player.close();
    }


    /**
     * This controllerUpdate function must be defined in order to
     * implement a ControllerListener interface. This 
     * function will be called whenever there is a media event
     */
    public synchronized void controllerUpdate(ControllerEvent event) {
	// If we're getting messages from a dead player, 
	// just leave
	if (player == null)
	    return;
	
	// When the player is Realized, get the visual 
	// and control components and add them to the Applet
	if (event instanceof RealizeCompleteEvent) {
	    if (progressBar != null) {
		panel.remove(progressBar);
		progressBar = null;
	    }

	    int width = 320;
	    int height = 0;
	    if (controlComponent == null)
		if (( controlComponent = 
		      player.getControlPanelComponent()) != null) {
		    
		    controlPanelHeight = controlComponent.getPreferredSize().height;
		    panel.add(controlComponent);
		    height += controlPanelHeight;
		}
	    if (visualComponent == null)
		if (( visualComponent =
		      player.getVisualComponent())!= null) {
		    panel.add(visualComponent);
		    Dimension videoSize = visualComponent.getPreferredSize();
		    videoWidth = videoSize.width;
		    videoHeight = videoSize.height;
		    width = videoWidth;
		    height += videoHeight;
		    visualComponent.setBounds(0, 0, videoWidth, videoHeight);
		}

	    panel.setBounds(0, 0, width, height);
	    if (controlComponent != null) {
		controlComponent.setBounds(0, videoHeight,
					   width, controlPanelHeight);
		controlComponent.invalidate();
	    }
	    
 	} else if (event instanceof CachingControlEvent) {
	    if (player.getState() > Controller.Realizing)
		return;
	    // Put a progress bar up when downloading starts, 
	    // take it down when downloading ends.
	    CachingControlEvent e = (CachingControlEvent) event;
	    CachingControl cc = e.getCachingControl();

	    // Add the bar if not already there ...
	    if (progressBar == null) {
	        if ((progressBar = cc.getControlComponent()) != null) {
		    panel.add(progressBar);
		    panel.setSize(progressBar.getPreferredSize());
		    validate();
		}
	    }
	} else if (event instanceof EndOfMediaEvent) {
	    // We've reached the end of the media; rewind and
	    // start over
            System.out.println("Entrou aqui EndOfMediaEvent");
            System.out.println("EstadoAtual= "+player.getState());
            System.out.println("Setando o tempo de inicio");            
	    player.setMediaTime(new Time((double)106*60));
	    //player.start();
	} else if (event instanceof ControllerErrorEvent) {
	    // Tell TypicalPlayerApplet.start() to call it a day
	    player = null;
	    Fatal(((ControllerErrorEvent)event).getMessage());
        } else if (event instanceof ControllerClosedEvent) {
	    panel.removeAll();
	}
    }

    void Fatal (String s) {
	// Applications will make various choices about what
	// to do here. We print a message
	System.err.println("FATAL ERROR: " + s);
	throw new Error(s); // Invoke the uncaught exception
			    // handler System.exit() is another
			    // choice.
	
    }
}

8 Respostas

M

ninguem tem uma ideia do que seja? to procurando no google mas n to achando nada…

M

consegui resolver…o problema é que estava extendendo a classe Applet…quando deveria usar JApplet…

S

boa ;). vc sabe com faz pra pegar a imagem em tempo real? Tipo uma webcam online que dá pra vc ver num site

M

nunca fiz…mas acho q já vi algo aqui no forum…

Agora to querendo recortar uma parte do vídeo de acordo com o tempo de inicio e fim que passar como parametro…

S

tenta fazer assim:
1.pega a stream inteira
2. mede o tamanho dela em bytes(ex: 2000 bytes)
3.mede o tempo total do filme(ex: 10 segundos)
4. Divida o tamanho pelo tempo e tera algo em torno de bytes/tempo(200 bytes por segundo).
5. crie outra stream
6. Veja qual tempo vc quer começar e pagar ( ex: 5 segundos e 7 segundos).

  1. passe pra stream 2 os bytes de 2005 a 2007

se funcionar posta aí ^^

M

shamanpyro,

vc tem algum exemplo ai? ou tem algum link?

valeu

S

Desculpe, mas bolei esse algoritmo na raça… não codifiquei nada ainda. Posso fazer isso mas vou demorar alguns dias; aqui no trampo ta bem pesado

D

mlobao…

estou com o mesmo problema que o seu em um código que estou utilizando… e tentei extender a classe JApplet… porém não consegui… teria como vc explicar dinovo o que fez para o seu Player funcionar!?

Criado 28 de agosto de 2008
Ultima resposta 15 de set. de 2008
Respostas 8
Participantes 3