Search code examples
androidkotlinretrofit2

upload audio file with binary body with retrofit


I need to upload audio file with binary body with retrofit like the image bellow in postman:

enter image description here

how can i upload audio file with binary body like the image with retrofit?

This is what I did but its not work:

@Multipart
@POST("upload")
fun uploadAudio(
    @Part audio_file: MultipartBody.Part
): Call<ModelGetAudioUrl>

And this is how I prepare audio file for multipartbody.Part:

enter image description here


Solution

  • I solve it by using okhttp:

    val client = OkHttpClient().newBuilder()
            .callTimeout(90, TimeUnit.SECONDS)
            .readTimeout(90, TimeUnit.SECONDS)
            .connectTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(90, TimeUnit.SECONDS)
            .build();
        val mediaType = "audio/wave".toMediaTypeOrNull();
        val body = RequestBody.create(mediaType, soundFile)
        val request = Request.Builder()
            .url("https://api.assemblyai.com/v2/upload")
            .method("POST", body)
            .addHeader("authorization", "99fa2a59e27e4688b9f7edcdc8ed7185")
            .addHeader("Transfer-Encoding", "chunked")
            .addHeader("Content-Type", "audio/wave")
            .build()
    
        Thread {
    
            try {
    
    
                val response = client.newCall(request).execute().use {
    
                    if (it.isSuccessful) {
    
                        val str = it.body?.string()
    
                        if (!str.isNullOrEmpty()) {
    
                            val json = JSONObject(str)
    
                            sendUrlToTranscript(json.getString("upload_url"))
    
                        }
    
                    }
    
                    context.runOnUiThread {
    
                        if (!it.isSuccessful) {
    
                            loading.hideDialog()
    
                        }
    
                    }
    
                }
    
            }catch (e: Exception) {
    
                e.printStackTrace()
                Log.d("uploadAudio", "uploadAudio: ${e.message}")
    
            }
    
    
        }.start()