MCPcopy Create free account
hub / github.com/badvision/jace / Media

Method Media

src/main/java/jace/core/Media.java:25–78  ·  view source on GitHub ↗
(String resourcePath)

Source from the content-addressed store, hash-verified

23 File tempFile;
24
25 public Media(String resourcePath) throws IOException {
26 System.out.println("Loading media: " + resourcePath);
27 byte[] oggFile;
28 try (InputStream oggStream = getClass().getResourceAsStream(resourcePath)) {
29 oggFile = oggStream.readAllBytes();
30 }
31
32 ByteBuffer oggBuffer = null;
33 STBVorbisInfo info = null;
34 ShortBuffer tempSampleBuffer = null;
35 try (MemoryStack stack = MemoryStack.stackPush()) {
36 oggBuffer = MemoryUtil.memAlloc(oggFile.length);
37 oggBuffer.put(oggFile);
38 oggBuffer.flip();
39 IntBuffer error = stack.callocInt(1);
40 Long decoder = STBVorbis.stb_vorbis_open_memory(oggBuffer, error, null);
41 if (decoder == null || decoder <= 0) {
42 throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + getError(error.get(0)) + " -- file is located at " + resourcePath);
43 }
44 info = STBVorbisInfo.malloc(stack);
45 STBVorbis.stb_vorbis_get_info(decoder, info);
46 totalSamples = STBVorbis.stb_vorbis_stream_length_in_samples(decoder);
47 totalDuration = STBVorbis.stb_vorbis_stream_length_in_seconds(decoder);
48 sampleRate = info.sample_rate();
49 isStereo = info.channels() == 2;
50 if (isStereo) {
51 totalSamples *= 2;
52 }
53
54 tempSampleBuffer = MemoryUtil.memAllocShort(2048);
55 sampleBuffer = ShortBuffer.allocate(totalSamples);
56 int sampleCount = 1;
57 int currentOffset = 0;
58 while (sampleCount > 0) {
59 sampleCount = STBVorbis.stb_vorbis_get_samples_short_interleaved(decoder, isStereo?2:1, tempSampleBuffer);
60 if (sampleCount == 0) {
61 break;
62 }
63 // copy sample buffer into byte buffer so we can deallocate, then transfer the buffer contents
64 sampleBuffer.put(currentOffset, tempSampleBuffer, 0, sampleCount * (isStereo ? 2 : 1));
65 tempSampleBuffer.rewind();
66 currentOffset += sampleCount * (isStereo ? 2 : 1);
67 }
68 STBVorbis.stb_vorbis_close(decoder);
69 sampleBuffer.rewind();
70 } catch (RuntimeException ex) {
71 throw ex;
72 } finally {
73 if (oggBuffer != null)
74 MemoryUtil.memFree(oggBuffer);
75 if (tempSampleBuffer != null)
76 MemoryUtil.memFree(tempSampleBuffer);
77 }
78 }
79
80 public String getError(int vorbisErrorCode) {
81 switch (vorbisErrorCode) {

Callers

nothing calls this directly

Calls 4

getErrorMethod · 0.95
allocateMethod · 0.80
rewindMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected