package com;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IPacket;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
public class Music
{
private String musicPath;
public Music(String mp)
{
musicPath = mp;
}
public IMediaWriter addMusic(int streamIndex, IMediaWriter orangeMovie,long total)
{
IContainer container = IContainer.make();
System.out.println("Adding music");
if (container.open(musicPath, IContainer.Type.READ, null) < 0)
{
throw new IllegalArgumentException("could not open file");
}
int numStreams = container.getNumStreams();
int audioStreamId = -1;
IStreamCoder audioCoder = null;
for(int i = 0; i < numStreams; i++)
{
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO)
{
audioStreamId = i;
audioCoder = coder;
audioCoder.setBitRate(container.getBitRate());
break;
}
}
if (audioStreamId == -1)
{
throw new RuntimeException("could not find audio stream in container");
}
audioCoder.setSampleFormat(IAudioSamples.Format.FMT_S16);
audioCoder.open();
IPacket packet = IPacket.make();
long timer = 0;
boolean stoper = false;
while(stoper == false)
{
container.readNextPacket(packet);
if (packet.getStreamIndex() == audioStreamId)
{
IAudioSamples samples = IAudioSamples.make(512, audioCoder.getChannels(),IAudioSamples.Format.FMT_S16 );
int offset = 0;
while(offset < packet.getSize())
{
int bytesDecoded = audioCoder.decodeAudio(samples, packet, offset);
if (bytesDecoded < 0)
{
throw new RuntimeException("got error decoding audio in");
}
offset += bytesDecoded;
if (samples.isComplete())
{
if(timer < total)
{
orangeMovie.encodeAudio(streamIndex, samples);
}
else
{
stoper = true;
}
}
}
timer += 26;
}
}
System.gc();
return orangeMovie;
}
}