播放来自API请求的音频文件。

huangapple go评论62阅读模式
英文:

Play audio file from api request

问题

I'm using ElevenLabs Api to convert text to speech, this api mainly returns byte[] as an audio, i tried to play it using MediaPlayer and AudioTrack but failed to do so, does anyone how to do that, Thank you in advance

  • Printed Bytes[]

[-61, -65, -61, -69, 80, -61, -124, 0, 0, 7, 40, 1, 103, -62, -76, 17, -62, -128, 1, -61, -113, -62, -99, -61, -83, 115, 24, -62, -80, 0, 0, 57, 38, 104, 0, -61, -108, 47, -61,

  • This is my api request

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, LAB_URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            // getting response as byte
                            playFile(response.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.d("VALUE","Response " + Arrays.toString(response.getBytes()));
                    }
                     }, new Response.ErrorListener() {
                   @Override
                  public void onErrorResponse(VolleyError error) {
                       Log.d("TAG","Error is " + error.getMessage());
                  }
             }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("accept", "audio/mpeg");
                headers.put("xi-api-key", LAB_KEY);
                headers.put("Content-Type", "application/json");
                return headers;
            }

            @Override
            public byte[] getBody() {
                JSONObject jsonBody = new JSONObject();
                try {
                    jsonBody.put("text", "Hello How are you man?");
                    JSONObject voiceSettings = new JSONObject();
                    voiceSettings.put("stability", 0);
                    voiceSettings.put("similarity_boost", 0);
                    jsonBody.put("voice_settings", voiceSettings);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return jsonBody.toString().getBytes();
            }
        };

        requestQueue.add(stringRequest);
    }
  • Play file using AudioTrack
        int sampleRate = 44100;
        int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        int bufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat);
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig, audioFormat, bufferSize, AudioTrack.MODE_STREAM);
        audioTrack.play();
        audioTrack.write(response, 0, response.length);
    }
  • Image of response from postman

播放来自API请求的音频文件。

英文:

I'm using ElevenLabs Api to convert text to speech , this api mainly returns byte[] as an audio , i tried to play it using MediaPlayer and AudioTrack but failed to do so, does anyone how to do that , Thank you in advance

  • Printed Bytes[]
 [-61, -65, -61, -69, 80, -61, -124, 0, 0, 7, 40, 1, 103, -62, -76, 17, -62, -128, 1, -61, -113, -62, -99, -61, -83, 115, 24, -62, -80, 0, 0, 57, 38, 104, 0, -61, -108, 47, -61,
  • This is my api request
  private  void elevenLab() throws JSONException {

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, LAB_URL, new Response.Listener&lt;String&gt;() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            // getting response as byte
                            playFile(response.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.d(&quot;VALUE&quot;,&quot;Response &quot; + Arrays.toString(response.getBytes()));
                    }
                     }, new Response.ErrorListener() {
                   @Override
                  public void onErrorResponse(VolleyError error) {
                       Log.d(&quot;TAG&quot;,&quot;Error is &quot; + error.getMessage());
                  }
             }) {
            @Override
            public Map&lt;String, String&gt; getHeaders() throws AuthFailureError {
                Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;();
                headers.put(&quot;accept&quot;, &quot;audio/mpeg&quot;);
                headers.put(&quot;xi-api-key&quot;, LAB_KEY);
                headers.put(&quot;Content-Type&quot;, &quot;application/json&quot;);
                return headers;
            }

            @Override
            public byte[] getBody() {
                JSONObject jsonBody = new JSONObject();
                try {
                    jsonBody.put(&quot;text&quot;, &quot;Hello How are you man?&quot;);
                    JSONObject voiceSettings = new JSONObject();
                    voiceSettings.put(&quot;stability&quot;, 0);
                    voiceSettings.put(&quot;similarity_boost&quot;, 0);
                    jsonBody.put(&quot;voice_settings&quot;, voiceSettings);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return jsonBody.toString().getBytes();
            }
        };

        requestQueue.add(stringRequest);
    }
  • Play file using AudioTrack

 private void playFile(byte[] response) throws IOException {
        int sampleRate = 44100;
        int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        int bufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat);
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig, audioFormat, bufferSize, AudioTrack.MODE_STREAM);
        audioTrack.play();
        audioTrack.write(response, 0, response.length);
    }
  • Image of response from postman

播放来自API请求的音频文件。

答案1

得分: 1

以下是翻译好的部分:

这段代码的主要问题是,您正在请求和处理字符串,而返回的对象是byte[]。

这里建议对您的代码进行以下更改:

Request<byte[]> request = new Request<byte[]>(Request.Method.POST, LAB_URL, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // 处理错误
    }}) {
    @Override
    public byte[] getBody() throws AuthFailureError {
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("text", responseMsg);
            JSONObject voiceSettings = new JSONObject();
            voiceSettings.put("stability", 0);
            voiceSettings.put("similarity_boost", 0);
            jsonBody.put("voice_settings", voiceSettings);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonBody.toString().getBytes();
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("accept", "audio/mpeg");
        headers.put("xi-api-key", "apikey");
        return headers;
    }

    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
        return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(byte[] response) {
        try {
            playFile(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

requestQueue.add(request);

请注意,这段代码没有检查响应是否为200。根据他们的规格,如果请求存在问题,它将返回application/json内容。

英文:

The main problem with this code is that you are requesting and operating on strings, while the returned object is byte[].

Here's a suggested change to your code:

 Request&lt;byte[]&gt; request = new Request&lt;byte[]&gt;(Request.Method.POST, LAB_URL, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}})
{
@Override
public byte[] getBody() throws AuthFailureError {
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put(&quot;text&quot;, responseMsg);
JSONObject voiceSettings = new JSONObject();
voiceSettings.put(&quot;stability&quot;, 0);
voiceSettings.put(&quot;similarity_boost&quot;, 0);
jsonBody.put(&quot;voice_settings&quot;, voiceSettings);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonBody.toString().getBytes();
}
@Override
public String getBodyContentType() {
return &quot;application/json&quot;;
}
@Override
public Map&lt;String, String&gt; getHeaders() throws AuthFailureError {
Map&lt;String, String&gt; headers = new HashMap&lt;&gt;();
headers.put(&quot;accept&quot;, &quot;audio/mpeg&quot;);
headers.put(&quot;xi-api-key&quot;, &quot;apikey&quot;);
return headers;
}
@Override
protected Response&lt;byte[]&gt; parseNetworkResponse(NetworkResponse response) {
return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(byte[] response) {
try {
playFile(response);
} catch (IOException e) {
e.printStackTrace();
}
}
};
requestQueue.add(request);

Note that this does not check if the response is 200. According to their specs it will return application/json content if something is wrong with the request.

huangapple
  • 本文由 发表于 2023年4月17日 00:56:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定