Transmision en RTP con JMF
Hola a todos,
Les pido ayuda sobre este pequeños problemo.
1. Tengo un proyecto sobre la api jmf, intento transmitir audio y video en la web para insertarla en mi pagina web
Resulta tengo una clase que hace la transmisión multimedia y otra que reproduce la transmisión
Al transmitir sobre una red local funciona bien (transmite y reproduce), pero e intentado de muchas maneras de transmitir en la red y no he obtenido ningún resultado....es como si no transmitiera nada, solo lo hace localmente en una red privada o una red wifi...
2.a veces la transmisión se distorsiona como una radio sin señal, suena solo ruido
espero me puedan ayuda les dejo el codigo...
:)
Transmisión
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.Controller;
import javax.media.ControllerClosedEvent;
import javax.media.ControllerErrorEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Format;
import javax.media.MediaLocator;
import javax.media.NoProcessorException;
import javax.media.Processor;
import javax.media.RealizeCompleteEvent;
import javax.media.control.TrackControl;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;
import javax.media.protocol.FileTypeDescriptor;
import javax.media.rtp.InvalidSessionAddressException;
import javax.media.rtp.Participant;
import javax.media.rtp.RTPControl;
import javax.media.rtp.RTPManager;
import javax.media.rtp.ReceiveStream;
import javax.media.rtp.ReceiveStreamListener;
import javax.media.rtp.SendStream;
import javax.media.rtp.SessionAddress;
import javax.media.rtp.SessionListener;
import javax.media.rtp.event.ByeEvent;
import javax.media.rtp.event.NewParticipantEvent;
import javax.media.rtp.event.NewReceiveStreamEvent;
import javax.media.rtp.event.ReceiveStreamEvent;
import javax.media.rtp.event.RemotePayloadChangeEvent;
import javax.media.rtp.event.SessionEvent;
import javax.media.rtp.event.StreamMappedEvent;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author user
*/
class MediaTransmitter implements ReceiveStreamListener, SessionListener, ControllerListener{
private ContentDescriptor cdA = new ContentDescriptor(ContentDescriptor.RAW_RTP);
private ContentDescriptor cdV = new ContentDescriptor(ContentDescriptor.RAW_RTP);
private JPlayerMain Main=null;
public String ipAddress;
public int port;
private DataSource dataOutput = null;
private MediaLocator mediaLocator = null;
private javax.media.Processor mediaProcessor = null;
private RTPManager Manager = RTPManager.newInstance();
private SessionAddress localAddress = null;
private SessionAddress remoteAddress = null;
private InetAddress IPAddress;
private InetAddress IPAddress2;
private SendStream sendStream;
public int c=0;
public boolean MultiCastMode=false;
public String FormatMP3=AudioFormat.MPEG_RTP;
public String FormatULAW=AudioFormat.ULAW_RTP;
public String FormatWAV=AudioFormat.GSM_RTP;
public String Formato=AudioFormat.ULAW_RTP;
public String FormatoV=VideoFormat.H261_RTP;
private static final Format[] FORMATS = new Format[]{
new AudioFormat(AudioFormat.LINEAR),
};
private static final ContentDescriptor CONTENT_DESCRIPTOR =
new ContentDescriptor(ContentDescriptor.RAW_RTP);
public MediaTransmitter(JPlayerMain M, String Dest, int prt ) {
Main=M;
ipAddress=Dest;
port=prt;
if(MultiCastMode==false){
try {
localAddress = new SessionAddress();
Manager.initialize(localAddress);
} catch (InvalidSessionAddressException ex) {
Logger.getLogger(MediaTransmitter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MediaTransmitter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public boolean setMulticastMode(boolean bol){
MultiCastMode=bol;
return MultiCastMode;
}
public Processor prepareProcessor(MediaLocator ML) {
boolean result=false;
Processor mediaProcessor=null;
MediaLocator mediaLocator=ML;
if (mediaLocator == null){
System.err.println("- Locator is null");
return null;
}
// Try to create a processor to handle the input media locator
try {
mediaProcessor = javax.media.Manager.createProcessor(mediaLocator);
} catch (NoProcessorException npe) {
System.err.println("- Couldn't create processor");
return null;
} catch (IOException ioe) {
System.out.println("- IOException creating processor");
return null;
}
// Wait for it to configure
result = waitForState(mediaProcessor, Processor.Configured);
if (result == false){
System.err.println("- Couldn't configure processor");
}
if(mediaProcessor!=null){
// Get the tracks from the processor
TrackControl [] tracks = mediaProcessor.getTrackControls();
// Do we have atleast one track?
if (tracks == null || tracks.length < 1)
System.err.println("- Couldn't find tracks in processor");
boolean programmed = false;
boolean typeaudio = true;
AudioFormat afmt;
VideoFormat vfmt;
// Search through the tracks for a Audio track
for (int i = 0; i < tracks.length; i++) {
Format format = tracks[i].getFormat();
if ( tracks[i].isEnabled() &&
format instanceof AudioFormat &&
!programmed) {
afmt = (AudioFormat)tracks[i].getFormat();
AudioFormat AFormat = new AudioFormat(Formato);
tracks[i].setFormat (AFormat);
System.out.println("Audio transmitted as:" );
System.out.println(" " + AFormat);
typeaudio=true;
// Assume succesful
programmed = true;
} else if ( tracks[i].isEnabled() &&
format instanceof VideoFormat &&
!programmed) {
vfmt = (VideoFormat)tracks[i].getFormat();
VideoFormat VFormat = new VideoFormat(FormatoV);
tracks[i].setFormat (VFormat);
System.out.println("Video transmitted as:" );
System.out.println(" " + VFormat);
typeaudio=false;
// Assume succesful
programmed = true;
} else {
tracks[i].setEnabled(false);
}
}
if (!programmed){
System.err.println("- Couldn't find Audio track");
}
// Set the output content descriptor to RAW_RTP
if(typeaudio){
mediaProcessor.setContentDescriptor(cdA);
}else{
mediaProcessor.setContentDescriptor(cdV);
}
// Realize the processor. This will internally create a flow
// graph and attempt to create an output datasource for ULAW/RTP
// Audio frames.
}
result = waitForState(mediaProcessor, Controller.Realized);
if (result == false){
System.err.println("- Couldn't realize processor");
return null;
}
// Get the output data source of the processor
mediaProcessor.addControllerListener(new StateListener());
System.out.println("- Processor OK");
return mediaProcessor;
}
private String createProcessor() {
if(dataOutput!=null){
try {
dataOutput.stop();
dataOutput=null;
mediaProcessor.stop();
mediaProcessor.close();
mediaProcessor.deallocate();
mediaProcessor=null;
} catch (IOException ex) {
Logger.getLogger(MediaTransmitter.class.getName()).log(Level.SEVERE, null, ex);
}
}
mediaLocator=new MediaLocator("file:/"+Main.TrackID);
mediaProcessor=prepareProcessor(mediaLocator);
// Get the output data source of the processor
dataOutput = mediaProcessor.getDataOutput();
mediaProcessor.addControllerListener(this);
return "- Processor OK";
}
private String createTransmitter() {
try {
IPAddress= InetAddress.getByName(ipAddress);
if(MultiCastMode==true){
IPAddress2= InetAddress.getByName("224.1.1.0");
port=3000;
localAddress=new SessionAddress(IPAddress2,port);
Manager.initialize(localAddress);
}
remoteAddress = new SessionAddress( IPAddress,port);
Manager.addTarget(remoteAddress);
} catch (Exception ex) {
}
try {
sendStream = Manager.createSendStream( dataOutput, c);
sendStream.start();
return "- Streamming OK";
} catch (Exception ex) {
}
return "- Error Creating Stream";
}
private Integer stateLock = new Integer(0);
private boolean failed = false;
Integer getStateLock() {
return stateLock;
}
void setFailed() {
failed = true;
}
class StateListener implements ControllerListener {
public void controllerUpdate(ControllerEvent ce) {
if (ce instanceof ControllerClosedEvent)
setFailed();
if (ce instanceof ControllerEvent) {
synchronized (getStateLock()) {
getStateLock().notifyAll();
}
}
}
}
private synchronized boolean waitForState(Processor p, int state) {
p.addControllerListener(new MediaTransmitter.StateListener());
failed = false;
if (state == Processor.Configured) {
p.configure();
} else if (state == Processor.Realized) {
p.realize();
}
// Wait until we get an event that confirms the
// success of the method, or a failure event.
// See StateListener inner class
while (p.getState() < state && !failed) {
synchronized (getStateLock()) {
try {
getStateLock().wait();
} catch (InterruptedException ie) {
return false;
}
}
}
if (failed)
return false;
else
return true;
}
public void stopTransmitting(){
if(mediaProcessor!=null){
mediaProcessor.stop();
mediaProcessor.close();
mediaProcessor=null;
System.out.println("Stopped Stream...");
}
}
public String SendStream(){
String S="Buiding Stream: "+createProcessor()+createTransmitter()+" on "+ipAddress+":"+port;
mediaProcessor.start();
return S;
}
public synchronized void controllerUpdate(ControllerEvent evt) {
System.err.println("Nuevo Evento: " + evt);
if (evt instanceof ControllerClosedEvent) {
}
if (evt instanceof EndOfMediaEvent) {
}
if (evt instanceof ControllerErrorEvent) {
mediaProcessor.removeControllerListener(this);
System.err.println(" Error: " + evt);
}
if (evt instanceof RealizeCompleteEvent) {
System.out.println("Conected!...");
}
}
public synchronized void update(SessionEvent evt) {
if (evt instanceof NewParticipantEvent) {
Participant p = ((NewParticipantEvent)evt).getParticipant();
System.err.println(" - A new participant had just joined: " + p.getCNAME());
p=null;
}
}
public synchronized void update( ReceiveStreamEvent evt) {
RTPManager mgr = (RTPManager)evt.getSource();
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent) {
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
System.exit(0);
}
else if (evt instanceof NewReceiveStreamEvent) {
try {
stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
javax.media.protocol.DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
if (ctl != null){
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
} else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else {
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
javax.media.Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
// Notify intialize() that a new stream had arrived.
} catch (Exception e) {
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
else if (evt instanceof StreamMappedEvent) {
if (stream != null && stream.getDataSource() != null) {
javax.media.protocol.DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent) {
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
}
}
}
Recepción
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author JJMM
*/
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.RenderedImage;
import java.util.logging.Logger;
import javax.media.*;
import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.media.control.FormatControl;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.rtp.Participant;
import javax.media.rtp.RTPControl;
import javax.media.rtp.RTPManager;
import javax.media.rtp.ReceiveStream;
import javax.media.rtp.ReceiveStreamListener;
import javax.media.rtp.SessionListener;
import javax.media.rtp.event.ByeEvent;
import javax.media.rtp.event.NewParticipantEvent;
import javax.media.rtp.event.NewReceiveStreamEvent;
import javax.media.rtp.event.ReceiveStreamEvent;
import javax.media.rtp.event.RemotePayloadChangeEvent;
import javax.media.rtp.event.SessionEvent;
import javax.media.rtp.event.StreamMappedEvent;
import javax.media.util.BufferToImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
class RTPClient extends Thread implements ReceiveStreamListener, SessionListener, ControllerListener {
private PlugInManager Plugins;
String srcUrl;
File F;
private Player p;
private MediaLocator src;
private String IP;
private int port;
private String jffmpegAudioDecoder = "net.sourceforge.jffmpeg.AudioDecoder";
private Codec codecAudio;
public String FormatMP3=AudioFormat.MPEG_RTP;
public String FormatULAW=AudioFormat.ULAW_RTP;
public String FormatWAV=AudioFormat.GSM_RTP;
public String Formato=AudioFormat.ULAW_RTP;
public static void main(String[] args) {
new RTPClient("localhost",2204);
}
public RTPClient(){
}
public RTPClient(String ip, int p) {
Format input1 = new AudioFormat(AudioFormat.ULAW_RTP);
Format output = new AudioFormat(AudioFormat.LINEAR);
Plugins.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1},
new Format[]{output},
Plugins.CODEC
);
port=p;
IP=ip;
srcUrl = "rtp://" + IP + ":"+port+"/audio";
System.out.println(srcUrl);
src = new MediaLocator(srcUrl);
F=new File(srcUrl);
plays();
}
public RTPClient(String ip, int p, String Formato) {
Format input1 = new AudioFormat(Formato);
Format output = new AudioFormat(AudioFormat.LINEAR);
Plugins.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1},
new Format[]{output},
Plugins.CODEC
);
port=p;
IP=ip;
srcUrl = "rtp://" + IP + ":"+port+"/audio";
System.out.println(srcUrl);
src = new MediaLocator(srcUrl);
F=new File(srcUrl);
plays();
}
public boolean plays(){
try {
if(p!=null){
p.removeControllerListener(this);
p.stop();
p=null;
}
p = Manager.createRealizedPlayer(src);
System.out.println("Conecting!...");
p.addControllerListener(this);
p.start();
System.out.println("Playing!...");
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
public boolean stops(){
if(p!=null){
p.removeControllerListener(this);
p.stop();
p.close();
p.deallocate();
p=null;
System.out.println("Stopped!...");
return true;
}else{
return false;
}
}
public boolean silence(){
if(p!=null){
p.getGainControl().setLevel(0);
System.out.println("Set Silence!...");
return true;
}else{
return false;
}
}
public boolean setVolume(double v){
double vol=(v*80);
vol=vol/100;
vol=vol/100;
if(p!=null){
p.getGainControl().setLevel((float)vol);
System.out.println("Set Volume!...");
return true;
}else{
return false;
}
}
public Component getVideo(){
if(p.getVisualComponent()!=null){
return p.getVisualComponent();
}else{
return null;
}
}
public void getVideoFrame(){
if(p.getVisualComponent()!=null){
JFrame Frame=new JFrame("Playing Video From: "+IP+":"+port);
Frame.add(p.getVisualComponent());
Frame.setAlwaysOnTop(true);
Frame.setResizable(false);
Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
Dimension ventana = p.getVisualComponent().getSize();
Frame.setLocation((pantalla.width - ventana.width) / 2, (pantalla.height - ventana.height) / 2);
Frame.setMaximumSize(pantalla);
Frame.setVisible(true);
}
}
public void getVideoCameraFrame(){
try {
CaptureDeviceInfo device = javax.media.cdm.CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
MediaLocator Locator = device.getLocator();
p = Manager.createRealizedPlayer(Locator);
p.start();
JFrame Frame=new JFrame("Playing Video From: Camera");
Frame.setSize(640,480);
Frame.getContentPane().setLayout(new javax.swing.BoxLayout(Frame.getContentPane(), javax.swing.BoxLayout.LINE_AXIS));
Frame.add(p.getVisualComponent());
Frame.setAlwaysOnTop(true);
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
} catch (Exception ex) {
System.out.println(ex);
}
}
public Component getVideoCamera(){
try {
CaptureDeviceInfo device = javax.media.cdm.CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
MediaLocator Locator = device.getLocator();
p = Manager.createRealizedPlayer(Locator);
p.start();
return p.getVisualComponent();
} catch (Exception ex) {
System.out.println(ex);
return null;
}
}
public Image capturePhoto(){
Image img=null;
if(p!=null)
{
FrameGrabbingControl fgc = (FrameGrabbingControl)p.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = fgc.grabFrame();
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
}else{
System.err.println("No se ha iniciado el player!");
return null;
}
return img;
}
public boolean saveImageFile(Image img,File imagenArch){
String formato = "JPEG";
try {
if(img !=null && imagenArch!=null)
ImageIO.write((RenderedImage) img, formato, imagenArch);
return true;
} catch (IOException ex) {
System.err.println("Error de escritura en Disco");
}
return false;
}
public String getDeviceListString(){
String List="";
Vector v=javax.media.cdm.CaptureDeviceManager.getDeviceList(null);
int t;
if((t=v.size())>0)
for(int i=0;i<t;i++)
{
List+=((CaptureDeviceInfo)v.elementAt(i)).getName()+"\n";
}
System.out.println(List);
return List;
}
public Format[] getFormats(String device){
CaptureDeviceInfo cdi=CaptureDeviceManager.getDevice(device);
Format []formats=cdi.getFormats();
return formats;
}
public void setFormat(String device,int indexformat){
if(p!=null)
p.stop();
Format []formatos=getFormats(device);
FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
formatControl.setFormat (formatos[indexformat]);
p.start();
}
public void run() {
while(true){
if(p!=null){
if(p.getState()==Player.Started){
if(p.getMediaTime()==p.getStopTime()){
p.stop();
plays();
}
}else{
System.out.println("");
}
try {
sleep(60000);
} catch (InterruptedException ex) {
Logger.getLogger(RTPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public synchronized void controllerUpdate(ControllerEvent evt) {
System.err.println("Nuevo Evento: " + evt);
if (evt instanceof ControllerClosedEvent) {
p.removeControllerListener(this);
p.stop();
plays();
}
if (evt instanceof EndOfMediaEvent) {
p.stop();
plays();
}
if (evt instanceof ControllerErrorEvent) {
p.removeControllerListener(this);
p.stop();
plays();
System.err.println(" Error: " + evt);
}
if (evt instanceof RealizeCompleteEvent) {
System.out.println("Conected!...");
}
if (evt instanceof StartEvent) {
}
}
public synchronized void update(SessionEvent evt) {
if (evt instanceof NewParticipantEvent) {
Participant p = ((NewParticipantEvent)evt).getParticipant();
System.err.println(" - A new participant had just joined: " + p.getCNAME());
p=null;
}
}
public synchronized void update( ReceiveStreamEvent evt) {
RTPManager mgr = (RTPManager)evt.getSource();
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent) {
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
System.exit(0);
}
else if (evt instanceof NewReceiveStreamEvent) {
try {
stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
javax.media.protocol.DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
if (ctl != null){
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
} else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else {
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
// Notify intialize() that a new stream had arrived.
} catch (Exception e) {
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
else if (evt instanceof StreamMappedEvent) {
if (stream != null && stream.getDataSource() != null) {
javax.media.protocol.DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent) {
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
}
}
}
- Inicie sesión o regístrese para enviar comentarios
Comentarios recientes
hace 8 semanas 4 días
hace 9 semanas 6 días
hace 16 semanas 4 días
hace 1 año 9 semanas
hace 2 años 21 semanas
hace 2 años 25 semanas
hace 2 años 32 semanas
hace 2 años 40 semanas
hace 2 años 43 semanas
hace 2 años 44 semanas