leonfancy / oggus

Oggus is a Java library for reading and writing Ogg and Opus stream. Opus packet structure is supported.
Do What The F*ck You Want To Public License
28 stars 0 forks source link

Trim opus file in ogg container #2

Open omkar-tenkale opened 3 years ago

omkar-tenkale commented 3 years ago

Can I use this library to Trim opus file in ogg container

I'm trying to avoid the large size ffmpeg lib and aiming for a small lib to trim/cut opus files in android

By any chance this library could help me?

leonfancy commented 3 years ago

It could help you, but not that straightway.

You should first read your audio as OggOpusStream

OggOpusStream oggOpusStream = OggOpusStream.from("audio/technology.opus");

// Get ID Header
IdHeader idHeader = oggOpusStream.getIdHeader();

// Get Comment Header
CommentHeader commentHeader = oggOpusStream.getCommentHeader();

while (true) {
    AudioDataPacket audioDataPacket = oggOpusStream.readAudioPacket();
    if (audioDataPacket == null) break;

    for (OpusPacket opusPacket : audioDataPacket.getOpusPackets()) {
        // Do something with opusPacket
    }
}

The create a new OutputStream, and encapsulate audioDataPacket into this OggPage and write to OutputStream.

// Create an output stream
OutputStream outputStream = ...;

// Create a new Ogg page
OggPage oggPage = OggPage.empty();

// Set header fields by calling setX() method
oggPage.setSerialNum(100);

// Add a data packet to this page
oggPage.addDataPacket(audioDataPacket.dump());

// Call dump() method to dump the OggPage object to byte array binary 
byte[] binary = oggPage.dump();

// Write the binary to stream
outputStream.write(binary);
omkar-tenkale commented 3 years ago

Thanks for detailed response I'll try to implement this

oggPage.setSerialNum(100); << Should 100 be fixed value or do i need to get it from somewhere?

omkar-tenkale commented 3 years ago

Also how will I map start and end positions in for loop

long trimStartMs;
long trimEndMs;

...
 for (OpusPacket opusPacket : audioDataPacket.getOpusPackets()) {
        if(packetLiesWithinTrimRange(opusPacket )){ writeToOutput(opusPacket); }
    }
...

private boolean packetLiesWithinTrimRange(OpusPacket packet){
   if(????????){ return true;}
  return false;
}
omkar-tenkale commented 2 years ago

@leonfancy ??