// I had partial success, the file plays but in media players the duration will be shown of original audio and the position jumping to trimmed section // with dependency on https://github.com/leonfancy/oggus // See issue: https://github.com/leonfancy/oggus/issues/2 import org.chenliang.oggus.ogg.OggPage; import org.chenliang.oggus.ogg.OggStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class OpusFileUtil { static long sampleRate = 48; static long streamPreskip = -1; static long streamGranulePosFirst; public static void trim(long fromMs, long toMs, InputStream source, File result) throws IOException { OggPage prevPage = null; Log.oneLine("OGGPAGETRIM START ======================"); OutputStream outputStream = new FileOutputStream(result); OggStream oggStream = OggStream.from(source); outputStream.write(oggStream.readPage().dump()); //1st id page outputStream.write(oggStream.readPage().dump()); //2nd comment page outputStream.flush(); while (true) { OggPage oggPage = oggStream.readPage(); if (oggPage == null) break; long pageMsStart = prevPage == null ? 0 : getPageMsEnd(prevPage); long pageMsEnd = getPageMsEnd(oggPage); Log.oneLine("OGGPAGETRIM MS_START " + pageMsStart + "OGGPAGETRIM MS_END " + pageMsEnd); if(pageMsStart > toMs){ break; } if (pageMsStart >= fromMs && pageMsEnd < toMs) { Log.oneLine("OGGPAGETRIM " + oggPage.getGranulePosition() + " IN RANGE --------------------"); outputStream.write(oggPage.dump()); outputStream.flush(); } if (prevPage == null) { //this is first page streamGranulePosFirst = oggPage.getGranulePosition(); } prevPage = oggPage; } } static long getPageMsEnd(OggPage page) { return (page.getGranulePosition() - streamGranulePosFirst - streamPreskip) / sampleRate; } }