# Audio

How to send a Audio task to UNLOCK API with createTask or in.php: task type names, every parameter, the solution object, proxy fields and code samples in 7 languages.

- **Price:** $0.25 per 1,000 ($0.00025 per task)
- **You send:** The audio as base64 (MP3), up to 500 KB, and its language
- **You get:** The words in the recording

## Task type names

This type has one name.

- `AudioTask`

## Task object

| Name | Type | Required | Description |
|---|---|---|---|
| `type` | String | Yes | Task type name. Matched in any letter case. AudioTask |
| `body` | String | Yes | The audio file as base64 (MP3), up to about 500 KB. |
| `lang` | String | No | Language spoken in the audio, for example en. |

Fields not listed here are passed to the solver as sent.

## Request

`POST https://unlock-api.com/createTask`

```json
{
  "clientKey": "YOUR_API_KEY",
  "task": {
    "type": "AudioTask",
    "body": "SUQzBAAAAAAAI1RTU0U...",
    "lang": "en"
  }
}
```

## Solution object

Returned in solution when status is ready.

| Name | Type | Description |
|---|---|---|
| `text` | String | The answer as text. |

```json
{
  "errorId": 0,
  "taskId": 1001,
  "status": "ready",
  "solution": {
    "text": "five three nine two"
  },
  "cost": "0.00025",
  "createTime": 1791640000,
  "endTime": 1791640014,
  "solveCount": 1
}
```

## Code samples

### Python

```python
import time, requests

API = "https://unlock-api.com"
KEY = "YOUR_API_KEY"

task = requests.post(f"{API}/createTask", json={
    "clientKey": KEY,
    "task": {
      "type": "AudioTask",
      "body": "SUQzBAAAAAAAI1RTU0U...",
      "lang": "en"
    }
}).json()
if task["errorId"]:
    raise SystemExit(task["errorCode"])

for _ in range(60):   # 60 x 5 s = the 5 minute task limit
    time.sleep(5)
    r = requests.post(f"{API}/getTaskResult", json={"clientKey": KEY, "taskId": task["taskId"]}).json()
    if r["errorId"]:
        raise SystemExit(f"{r['errorCode']}: {r.get('errorDescription', '')}")   # failed tasks are refunded
    if r["status"] == "ready":
        print(r["solution"]["text"])
        break
else:
    raise SystemExit("timed out")
```

### Node.js

```javascript
const API = "https://unlock-api.com";
const KEY = "YOUR_API_KEY";
const post = (path, body) => fetch(API + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).then((r) => r.json());

const task = await post("/createTask", {
  clientKey: KEY,
  task: {
    "type": "AudioTask",
    "body": "SUQzBAAAAAAAI1RTU0U...",
    "lang": "en"
  },
});
if (task.errorId) throw new Error(task.errorCode);

let solution = null;
for (let n = 0; n < 60 && !solution; n++) { // 60 x 5 s = the 5 minute task limit
  await new Promise((r) => setTimeout(r, 5000));
  const r = await post("/getTaskResult", { clientKey: KEY, taskId: task.taskId });
  if (r.errorId) throw new Error(r.errorCode + ": " + r.errorDescription); // failed tasks are refunded
  if (r.status === "ready") solution = r.solution;
}
if (!solution) throw new Error("timed out");
console.log(solution.text);
```

### PHP

```php
<?php
$api = "https://unlock-api.com";
$key = "YOUR_API_KEY";
function post($url, $body) {
  $c = curl_init($url);
  curl_setopt_array($c, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($body)]);
  return json_decode(curl_exec($c), true);
}
$task = post("$api/createTask", ["clientKey" => $key, "task" => json_decode('{"type":"AudioTask","body":"SUQzBAAAAAAAI1RTU0U...","lang":"en"}', true)]);
if ($task["errorId"]) exit($task["errorCode"]);
for ($n = 0; $n < 60; $n++) { // 60 x 5 s = the 5 minute task limit
  sleep(5);
  $r = post("$api/getTaskResult", ["clientKey" => $key, "taskId" => $task["taskId"]]);
  if ($r["errorId"]) exit($r["errorCode"] . ": " . $r["errorDescription"]); // failed tasks are refunded
  if ($r["status"] === "ready") break;
}
if ($r["status"] !== "ready") exit("timed out");
print_r($r["solution"]["text"]);
```

### Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

const api = "https://unlock-api.com"
const key = "YOUR_API_KEY"

func post(method string, body map[string]any) map[string]any {
	b, _ := json.Marshal(body)
	res, err := http.Post(api+"/"+method, "application/json", bytes.NewReader(b))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	var out map[string]any
	json.NewDecoder(res.Body).Decode(&out)
	return out
}

func main() {
	task := post("createTask", map[string]any{
		"clientKey": key,
		"task": map[string]any{
			"type": "AudioTask",
			"body": "SUQzBAAAAAAAI1RTU0U...",
			"lang": "en",
		},
	})
	if task["errorId"].(float64) != 0 {
		panic(task["errorCode"])
	}
	for n := 0; n < 60; n++ { // 60 x 5 s = the 5 minute task limit
		time.Sleep(5 * time.Second)
		r := post("getTaskResult", map[string]any{"clientKey": key, "taskId": task["taskId"]})
		if r["errorId"].(float64) != 0 {
			panic(r["errorCode"]) // failed tasks are refunded
		}
		if r["status"] == "ready" {
			fmt.Println(r["solution"])
			return
		}
	}
	panic("timed out")
}
```

### Java

```java
import java.net.URI;
import java.net.http.*;
import java.util.regex.*;

public class Solve {
  static final String API = "https://unlock-api.com", KEY = "YOUR_API_KEY";
  static final HttpClient HTTP = HttpClient.newHttpClient();

  static String post(String method, String json) throws Exception {
    var req = HttpRequest.newBuilder(URI.create(API + "/" + method))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json)).build();
    return HTTP.send(req, HttpResponse.BodyHandlers.ofString()).body();
  }

  public static void main(String[] args) throws Exception {
    String task = "{\"type\":\"AudioTask\",\"body\":\"SUQzBAAAAAAAI1RTU0U...\",\"lang\":\"en\"}";
    String created = post("createTask", "{\"clientKey\":\"" + KEY + "\",\"task\":" + task + "}");
    Matcher id = Pattern.compile("\"taskId\":(\\d+)").matcher(created);
    if (!id.find()) throw new RuntimeException(created);
    for (int n = 0; n < 60; n++) { // 60 x 5 s = the 5 minute task limit
      Thread.sleep(5000);
      String r = post("getTaskResult", "{\"clientKey\":\"" + KEY + "\",\"taskId\":" + id.group(1) + "}");
      if (r.contains("\"errorId\":1")) throw new RuntimeException(r); // failed tasks are refunded
      if (r.contains("\"status\":\"ready\"")) { System.out.println(r); return; }
    }
    throw new RuntimeException("timed out");
  }
}
```

### C#

```csharp
using System.Net.Http.Json;
using System.Text.Json;

const string Api = "https://unlock-api.com";
const string Key = "YOUR_API_KEY";
var http = new HttpClient();

async Task<JsonElement> Post(string method, object body) =>
    await (await http.PostAsJsonAsync($"{Api}/{method}", body)).Content.ReadFromJsonAsync<JsonElement>();

var task = await Post("createTask", new {
    clientKey = Key,
    task = JsonSerializer.Deserialize<JsonElement>("""
        {"type":"AudioTask","body":"SUQzBAAAAAAAI1RTU0U...","lang":"en"}
        """)
});
if (task.GetProperty("errorId").GetInt32() != 0) throw new Exception(task.GetProperty("errorCode").GetString());

for (var n = 0; n < 60; n++) { // 60 x 5 s = the 5 minute task limit
    await Task.Delay(5000);
    var r = await Post("getTaskResult", new { clientKey = Key, taskId = task.GetProperty("taskId").GetInt64() });
    if (r.GetProperty("errorId").GetInt32() != 0) throw new Exception(r.GetProperty("errorCode").GetString()); // failed tasks are refunded
    if (r.GetProperty("status").GetString() == "ready") { Console.WriteLine(r.GetProperty("solution")); return; }
}
throw new Exception("timed out");
```

### cURL

```bash
curl -s https://unlock-api.com/createTask \
  -H "Content-Type: application/json" \
  -d '{"clientKey":"YOUR_API_KEY","task":{"type":"AudioTask","body":"SUQzBAAAAAAAI1RTU0U...","lang":"en"}}'
# {"errorId":0,"taskId":1001}

curl -s https://unlock-api.com/getTaskResult \
  -H "Content-Type: application/json" \
  -d '{"clientKey":"YOUR_API_KEY","taskId":1001}'
# {"errorId":0,"status":"processing"}  then  {"errorId":0,"status":"ready","solution":{...},"cost":"0.001"}
```

## in.php form method

The same task with the classic form request. res.php returns the answer as text.

```bash
curl -s "https://unlock-api.com/in.php" -d "key=YOUR_API_KEY&method=audio&lang=en&body=BASE64_AUDIO&json=1"
# {"status":1,"request":"1001"}

curl -s "https://unlock-api.com/res.php?key=YOUR_API_KEY&action=get&id=1001&json=1"
# {"status":0,"request":"CAPCHA_NOT_READY"}  then  {"status":1,"request":"ANSWER"}
```
