Last active
September 20, 2024 12:45
-
-
Save omkar-tenkale/216f9d89a41fe2e1fea0febf042209e0 to your computer and use it in GitHub Desktop.
Trim opus without FFMPEG in JAVA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment