Girley Gonzales
Girley Gonzales

Reputation: 79

IBM speech to text- How can I convert MP3 audio file into an array of bytes

IBM speech to text- How can I convert MP3 audio file into an array of bytes to send to a server in IBM Watson to convert the audio into text using speech to text API

Upvotes: 0

Views: 220

Answers (1)

murgupluoglu
murgupluoglu

Reputation: 7205

You can convert mp3 to bytearray like this;

fun convert(context: Context): ByteArray {

        val outputFile = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).absolutePath + "/sample.mp3"

        var soundBytes = ByteArray(0)
        try {
            val inputStream = context.contentResolver.openInputStream(Uri.fromFile(File(outputFile)))
            soundBytes = IOUtils.toByteArray(inputStream)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return soundBytes
}

Java

public byte[] convert(Context context) {

    String outputFile =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/sample.mp3";

    byte[] soundBytes = new byte[0];
    try {
        InputStream inputStream =
                context.getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));

        soundBytes = new byte[inputStream.available()];
        soundBytes = IOUtils.toByteArray(inputStream);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return soundBytes;
}

Upvotes: 0

Related Questions