How to read an FLV file using the FLVUtils API

The following example code uses the internal FLVUtils class to read a .flv file:

public void debugFLVFile(File file)
{
	try
	{
		BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(file));
		FLVUtils.readHeader(inStream); 
		while(true)
		{
			AMFPacket packet = FLVUtils.readChunk(inStream);
			if (packet == null)
				break;

			int type = packet.getType();
			switch(type)
			{
			case IVHost.CONTENTTYPE_AUDIO:
				System.out.println("packet[aud]: type:"+packet.getType()+" tc:"+packet.getAbsTimecode()+" size:"+packet.getSize()+" codec:"+Integer.toHexString(0x0ff&FLVUtils.getAudioCodec(packet.getFirstByte()))+" isCodecConfig:"+FLVUtils.isAudioCodecConfig(packet));
				break;
			case IVHost.CONTENTTYPE_VIDEO:
				System.out.println("packet[vid]: type:"+packet.getType()+" tc:"+packet.getAbsTimecode()+" size:"+packet.getSize()+" codec:"+Integer.toHexString(0x0ff&FLVUtils.getVideoCodec(packet.getFirstByte()))+" isCodecConfig:"+FLVUtils.isVideoCodecConfig(packet)+" isKey:"+FLVUtils.isVideoKeyFrame(packet));
				break;
			default:
			{
				System.out.println("packet[dat]: type:"+packet.getType()+" tc:"+packet.getAbsTimecode()+" size:"+packet.getSize());
				try
				{
					while(true)
					{
						AMFDataList dataList = new AMFDataList(packet.getData());
						if (dataList == null)
							break;
						System.out.println(dataList.toString());
						break;
					}
				}
				catch(Exception e)
				{
					WMSLoggerFactory.getLogger(null).info("debugFLVFile: data: "+e.toString());
				}
				break;
			}
			}
		}
		inStream.close();
	}
	catch(Exception e)
	{
		WMSLoggerFactory.getLogger(null).info("debugFLVFile: "+e.toString());
	}
}
Here is code to append one file onto another:
 
public void appendFLVFile(File base, File toAppend)
{
	try
	{
		BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(toAppend, true));

		long baseTimecode = FLVUtils.getLastTC(base);

		BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(toAppend));
		FLVUtils.readHeader(inStream);
		AMFPacket metaData = FLVUtils.readChunk(inStream);
		long timecode = 0;
		while(true)
		{
			AMFPacket packet = FLVUtils.readChunk(inStream);
			if (packet == null)
				break;

			timecode = baseTimecode + packet.getAbsTimecode();

			FLVUtils.writeChunk(outStream, packet.getDataBuffer(), packet.getSize(), timecode, (byte)packet.getType());
		}

		inStream.close();
		outStream.close();

		FLVUtils.writeDuration(base, timecode);
	}
	catch(Exception e)
	{
		WMSLoggerFactory.getLogger(null).info("appendFLVFile: "+e.toString());
	}
}

Originally Published: 10-03-2010.

If you're having problems or want to discuss this article, post in our forum.