Kyryl Zotov
Kyryl Zotov

Reputation: 1968

Convert ByteArray to ShortArray

I have byte arrays with audio data in Kotlin/Java.

When I use following code The ShortBuffer is created but the short[] inside is is null.

    var short1 = ByteBuffer.wrap(samples.data).order(ByteOrder.BIG_ENDIAN).asShortBuffer()

when I invoke fucntion .array() its impossible to convert as short[] is null in buffer.

I'm operating with arrays/buffers in a wrong way?

Sample data is byte[] that contains Audio data in Android WebRtc

Upvotes: 1

Views: 516

Answers (1)

MarcoLucidi
MarcoLucidi

Reputation: 2177

the array() method of ShortBuffer is an optional operation and will work only when the ShortBuffer is backed by a short array (short[]).

public final short[] array()

Returns the short array that backs this buffer (optional operation).

Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.

Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array.

since your ShortBuffer is not backed by a short[], because is created by a ByteBuffer, the array() method will throw UnsupportedOperationException.

you can use the hasArray() method to check whether is safe to call array().

Upvotes: 3

Related Questions