> ## Documentation Index
> Fetch the complete documentation index at: https://docs.api.box/llms.txt
> Use this file to discover all available pages before exploring further.

# WAV Format Conversion Callbacks

> When WAV format conversion tasks are completed, the system will send results to your provided callback URL via POST request

When you submit a task to the WAV format conversion API, you can use the `callBackUrl` parameter to set a callback URL. When the task is completed, the system will automatically push the results to your specified address.

## Callback Mechanism Overview

<Info>
  The callback mechanism eliminates the need to poll the API for task status. The system will proactively push task completion results to your server.
</Info>

### Callback Timing

The system will send callback notifications in the following situations:

* WAV format conversion completed
* WAV conversion task failed
* Error occurred during task processing

<Note>
  WAV format conversion has only one callback stage, providing the download URL upon completion
</Note>

### Callback Method

* **HTTP Method**: POST
* **Content Type**: application/json
* **Timeout**: 15 seconds

## Callback Request Format

When the task is completed, the system will send a POST request to your `callBackUrl` in the following format:

<CodeGroup>
  ```json WAV Conversion Complete Callback theme={null}
  {
    "code": 200,
    "msg": "success",
    "data": {
      "audioWavUrl": "https://example.com/s/04e6****e727.wav",
      "task_id": "988e****c8d3"
    }
  }
  ```

  ```json WAV Conversion Failed Callback theme={null}
  {
    "code": 400,
    "msg": "WAV conversion failed, invalid source audio",
    "data": {
      "task_id": "988e****c8d3",
      "audioWavUrl": null
    }
  }
  ```
</CodeGroup>

## Status Code Description

<ParamField path="code" type="integer" required>
  Callback status code indicating task processing result:

  | Status Code | Description                                                |
  | ----------- | ---------------------------------------------------------- |
  | 200         | Success - WAV conversion completed                         |
  | 400         | Bad Request - Invalid source audio or parameter error      |
  | 401         | Unauthorized - Invalid API key                             |
  | 429         | Insufficient Credits - Account credit balance insufficient |
  | 500         | Server Error - Please retry later                          |
</ParamField>

<ParamField path="msg" type="string" required>
  Status message providing detailed status description
</ParamField>

<ParamField path="data.task_id" type="string" required>
  Task ID, consistent with the taskId returned when you submitted the task
</ParamField>

<ParamField path="data.audioWavUrl" type="string">
  WAV format audio file download URL (returned on success)
</ParamField>

## Callback Reception Examples

Here are example codes for receiving callbacks in various popular programming languages:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const express = require('express');
    const fs = require('fs');
    const https = require('https');
    const app = express();

    app.use(express.json());

    app.post('/wav-callback', (req, res) => {
      const { code, msg, data } = req.body;
      
      console.log('Received WAV conversion callback:', {
        taskId: data.task_id,
        status: code,
        message: msg
      });
      
      if (code === 200 && data.audioWavUrl) {
        // WAV conversion successful
        console.log(`WAV file ready: ${data.audioWavUrl}`);
        
        // Download WAV file
        downloadWavFile(data.audioWavUrl, data.task_id);
        
      } else {
        // Task failed
        console.log('WAV conversion failed:', msg);
        
        // Handle failure cases...
        if (code === 400) {
          console.log('Invalid source audio or parameter error');
        } else if (code === 429) {
          console.log('Insufficient credits');
        } else if (code === 500) {
          console.log('Server internal error');
        }
      }
      
      // Return 200 status code to confirm callback received
      res.status(200).json({ status: 'received' });
    });

    function downloadWavFile(url, taskId) {
      const filename = `wav_${taskId}.wav`;
      const file = fs.createWriteStream(filename);
      
      https.get(url, (response) => {
        response.pipe(file);
        
        file.on('finish', () => {
          file.close();
          console.log(`WAV file downloaded: ${filename}`);
        });
      }).on('error', (err) => {
        console.error('WAV download failed:', err.message);
      });
    }

    app.listen(3000, () => {
      console.log('WAV callback server running on port 3000');
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from flask import Flask, request, jsonify
    import requests

    app = Flask(__name__)

    @app.route('/wav-callback', methods=['POST'])
    def handle_callback():
        data = request.json
        
        code = data.get('code')
        msg = data.get('msg')
        callback_data = data.get('data', {})
        task_id = callback_data.get('task_id')
        wav_url = callback_data.get('audioWavUrl')
        
        print(f"Received WAV conversion callback: {task_id}, Status: {code}")
        
        if code == 200 and wav_url:
            # WAV conversion successful
            print(f"WAV file ready: {wav_url}")
            
            # Download WAV file
            download_wav_file(wav_url, task_id)
            
        else:
            # Task failed
            print(f"WAV conversion failed: {msg}")
            
            # Handle failure cases...
            if code == 400:
                print("Invalid source audio or parameter error")
            elif code == 429:
                print("Insufficient credits")
            elif code == 500:
                print("Server internal error")
        
        # Return 200 status code to confirm callback received
        return jsonify({'status': 'received'}), 200

    def download_wav_file(url, task_id):
        """Download WAV file from the provided URL"""
        try:
            response = requests.get(url)
            if response.status_code == 200:
                filename = f"wav_{task_id}.wav"
                with open(filename, "wb") as f:
                    f.write(response.content)
                print(f"WAV file downloaded: {filename}")
            else:
                print(f"Failed to download WAV file: HTTP {response.status_code}")
        except Exception as e:
            print(f"WAV download failed: {e}")

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=3000)
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
    header('Content-Type: application/json');

    // Get POST data
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $code = $data['code'] ?? null;
    $msg = $data['msg'] ?? '';
    $callbackData = $data['data'] ?? [];
    $taskId = $callbackData['task_id'] ?? '';
    $wavUrl = $callbackData['audioWavUrl'] ?? '';

    error_log("Received WAV conversion callback: $taskId, Status: $code");

    if ($code === 200 && $wavUrl) {
        // WAV conversion successful
        error_log("WAV file ready: $wavUrl");
        
        // Download WAV file
        downloadWavFile($wavUrl, $taskId);
        
    } else {
        // Task failed
        error_log("WAV conversion failed: $msg");
        
        // Handle failure cases...
        if ($code === 400) {
            error_log("Invalid source audio or parameter error");
        } elseif ($code === 429) {
            error_log("Insufficient credits");
        } elseif ($code === 500) {
            error_log("Server internal error");
        }
    }

    function downloadWavFile($url, $taskId) {
        try {
            $wavContent = file_get_contents($url);
            if ($wavContent !== false) {
                $filename = "wav_{$taskId}.wav";
                file_put_contents($filename, $wavContent);
                error_log("WAV file downloaded: $filename");
            } else {
                error_log("Failed to download WAV file from URL");
            }
        } catch (Exception $e) {
            error_log("WAV download failed: " . $e->getMessage());
        }
    }

    // Return 200 status code to confirm callback received
    http_response_code(200);
    echo json_encode(['status' => 'received']);
    ?>
    ```
  </Tab>
</Tabs>

## Best Practices

<Tip>
  ### WAV Conversion Callback Configuration

  1. **File Management**: Implement proper file naming conventions for downloaded WAV files
  2. **Storage Planning**: Ensure adequate storage space for high-quality WAV files
  3. **Quality Verification**: Verify WAV file integrity after download
  4. **Metadata Preservation**: Maintain track information and metadata with WAV files
  5. **Batch Processing**: Consider batch conversion for multiple tracks
  6. **Cleanup**: Implement cleanup procedures for temporary files
</Tip>

<Warning>
  ### WAV-Specific Considerations

  * WAV files are typically larger than MP3 files due to lossless compression
  * Download times may be longer due to file size
  * Ensure sufficient bandwidth for WAV file downloads
  * WAV format provides maximum audio quality for professional use
  * Consider storage costs for large WAV file collections
</Warning>

## Troubleshooting

Common issues specific to WAV conversion callbacks:

<AccordionGroup>
  <Accordion title="Download Issues">
    * Verify the WAV URL is accessible and not expired
    * Check network connectivity and bandwidth
    * Ensure sufficient local storage space
    * Verify download permissions and file paths
  </Accordion>

  <Accordion title="Quality and Format">
    * Confirm the source audio quality meets WAV conversion requirements
    * Check if the original audio file is corrupted
    * Verify that the converted WAV maintains expected quality
    * Test WAV file playback in different audio applications
  </Accordion>

  <Accordion title="File Management">
    * Implement proper file naming to avoid conflicts
    * Monitor storage usage for WAV file collections
    * Consider automated cleanup for old WAV files
    * Verify file integrity after download completion
  </Accordion>
</AccordionGroup>

## Alternative Solutions

If you cannot use the callback mechanism, you can also use polling:

<Card title="Poll WAV Results" icon="radar" href="/suno-api/get-wav-conversion-details">
  Use the Get WAV Conversion Details interface to regularly query conversion task status. Recommend querying every 20 seconds.
</Card>
