> ## 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.

# Music Extension Callbacks

> When music extension tasks are completed, the system will send results to your provided callback URL via POST request

When you submit a task to the music extension 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:

* Text generation completed (`text` stage)
* First extended music track generated (`first` stage)
* All extended music tracks generated (`complete` stage)
* Music extension task failed
* Error occurred during task processing

### 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 Text Generation Complete Callback theme={null}
  {
    "code": 200,
    "msg": "Text generation completed successfully.",
    "data": {
      "callbackType": "text",
      "task_id": "2fac****9f72",
      "data": []
    }
  }
  ```

  ```json First Track Complete Callback theme={null}
  {
    "code": 200,
    "msg": "First track generated successfully.",
    "data": {
      "callbackType": "first",
      "task_id": "2fac****9f72",
      "data": [
        {
          "id": "8551****662c",
          "audio_url": "https://example.cn/****.mp3",
          "source_audio_url": "https://example.cn/****.mp3",
          "stream_audio_url": "https://example.cn/****",
          "source_stream_audio_url": "https://example.cn/****",
          "image_url": "https://example.cn/****.jpeg",
          "source_image_url": "https://example.cn/****.jpeg",
          "prompt": "[Verse] Night city lights shining bright",
          "model_name": "chirp-v3-5",
          "title": "Iron Man Extended",
          "tags": "electrifying, rock",
          "createTime": "2025-01-01 00:00:00",
          "duration": 278.44
        }
      ]
    }
  }
  ```

  ```json All Tracks Complete Callback theme={null}
  {
    "code": 200,
    "msg": "All generated successfully.",
    "data": {
      "callbackType": "complete",
      "task_id": "2fac****9f72",
      "data": [
        {
          "id": "8551****662c",
          "audio_url": "https://example.cn/****.mp3",
          "source_audio_url": "https://example.cn/****.mp3",
          "stream_audio_url": "https://example.cn/****",
          "source_stream_audio_url": "https://example.cn/****",
          "image_url": "https://example.cn/****.jpeg",
          "source_image_url": "https://example.cn/****.jpeg",
          "prompt": "[Verse] Night city lights shining bright",
          "model_name": "chirp-v3-5",
          "title": "Iron Man Extended",
          "tags": "electrifying, rock",
          "createTime": "2025-01-01 00:00:00",
          "duration": 278.44
        }
      ]
    }
  }
  ```

  ```json Failed Callback theme={null}
  {
    "code": 400,
    "msg": "Failed to extend music, invalid audio source",
    "data": {
      "callbackType": "failed",
      "task_id": "2fac****9f72",
      "data": []
    }
  }
  ```
</CodeGroup>

## Status Code Description

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

  | Status Code | Description                                                  |
  | ----------- | ------------------------------------------------------------ |
  | 200         | Success - Music extension completed                          |
  | 400         | Bad Request - Invalid source audio or parameter error        |
  | 401         | Unauthorized - Invalid API key                               |
  | 413         | Content Too Long - Prompt or style description exceeds limit |
  | 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.callbackType" type="string" required>
  Callback type indicating the current callback stage:

  * `text`: Text generation completed
  * `first`: First extended music track generated
  * `complete`: All extended music tracks generated
  * `failed`: Task failed
</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.data" type="array">
  Music extension result information, returned on success
</ParamField>

<ParamField path="data.data[].id" type="string">
  Audio unique identifier (audioId)
</ParamField>

<ParamField path="data.data[].audio_url" type="string">
  Extended audio file download link
</ParamField>

<ParamField path="data.data[].source_audio_url" type="string">
  Original extended audio file download link
</ParamField>

<ParamField path="data.data[].stream_audio_url" type="string">
  Streaming audio playback link
</ParamField>

<ParamField path="data.data[].image_url" type="string">
  Music cover image link
</ParamField>

<ParamField path="data.data[].prompt" type="string">
  Extension prompt used
</ParamField>

<ParamField path="data.data[].model_name" type="string">
  AI model name used for extension
</ParamField>

<ParamField path="data.data[].title" type="string">
  Extended music title
</ParamField>

<ParamField path="data.data[].tags" type="string">
  Music style tags
</ParamField>

<ParamField path="data.data[].createTime" type="string">
  Creation time
</ParamField>

<ParamField path="data.data[].duration" type="number">
  Extended audio duration (seconds)
</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 app = express();

    app.use(express.json());

    app.post('/extend-callback', (req, res) => {
      const { code, msg, data } = req.body;
      
      console.log('Received music extension callback:', {
        taskId: data.task_id,
        callbackType: data.callbackType,
        status: code,
        message: msg
      });
      
      if (code === 200) {
        // Task successful
        const { callbackType, data: musicData } = data;
        
        switch (callbackType) {
          case 'text':
            console.log('Text generation completed');
            break;
            
          case 'first':
            console.log('First extended music track generated');
            if (musicData.length > 0) {
              console.log(`Extended music title: ${musicData[0].title}`);
              console.log(`Audio link: ${musicData[0].audio_url}`);
              console.log(`Duration: ${musicData[0].duration} seconds`);
            }
            break;
            
          case 'complete':
            console.log('All extended music tracks generated');
            console.log(`Total ${musicData.length} extended tracks:`);
            musicData.forEach((track, index) => {
              console.log(`Track ${index + 1}: ${track.title} - ${track.audio_url}`);
            });
            
            // Process extended music
            // Can download music, save locally, etc.
            break;
        }
        
      } else {
        // Task failed
        console.log('Music extension 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' });
    });

    app.listen(3000, () => {
      console.log('Extension 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('/extend-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')
        callback_type = callback_data.get('callbackType')
        music_data = callback_data.get('data', [])
        
        print(f"Received music extension callback: {task_id}, Type: {callback_type}, Status: {code}")
        
        if code == 200:
            # Task successful
            if callback_type == 'text':
                print("Text generation completed")
                
            elif callback_type == 'first':
                print("First extended music track generated")
                if music_data:
                    track = music_data[0]
                    print(f"Extended music title: {track.get('title')}")
                    print(f"Audio link: {track.get('audio_url')}")
                    print(f"Duration: {track.get('duration')} seconds")
                    
            elif callback_type == 'complete':
                print("All extended music tracks generated")
                print(f"Total {len(music_data)} extended tracks:")
                
                for i, track in enumerate(music_data):
                    print(f"Track {i + 1}: {track.get('title')} - {track.get('audio_url')}")
                    
                    # Download extended music example
                    try:
                        audio_url = track.get('audio_url')
                        if audio_url:
                            response = requests.get(audio_url)
                            if response.status_code == 200:
                                filename = f"extended_music_{task_id}_{i + 1}.mp3"
                                with open(filename, "wb") as f:
                                    f.write(response.content)
                                print(f"Extended music saved as {filename}")
                    except Exception as e:
                        print(f"Music download failed: {e}")
                        
        else:
            # Task failed
            print(f"Music extension 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

    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'] ?? '';
    $callbackType = $callbackData['callbackType'] ?? '';
    $musicData = $callbackData['data'] ?? [];

    error_log("Received music extension callback: $taskId, Type: $callbackType, Status: $code");

    if ($code === 200) {
        // Task successful
        switch ($callbackType) {
            case 'text':
                error_log("Text generation completed");
                break;
                
            case 'first':
                error_log("First extended music track generated");
                if (!empty($musicData)) {
                    $track = $musicData[0];
                    error_log("Extended music title: " . ($track['title'] ?? ''));
                    error_log("Audio link: " . ($track['audio_url'] ?? ''));
                    error_log("Duration: " . ($track['duration'] ?? 0) . " seconds");
                }
                break;
                
            case 'complete':
                error_log("All extended music tracks generated");
                error_log("Total " . count($musicData) . " extended tracks:");
                
                foreach ($musicData as $index => $track) {
                    $title = $track['title'] ?? '';
                    $audioUrl = $track['audio_url'] ?? '';
                    error_log("Track " . ($index + 1) . ": $title - $audioUrl");
                    
                    // Download extended music example
                    try {
                        if ($audioUrl) {
                            $audioContent = file_get_contents($audioUrl);
                            if ($audioContent !== false) {
                                $filename = "extended_music_{$taskId}_" . ($index + 1) . ".mp3";
                                file_put_contents($filename, $audioContent);
                                error_log("Extended music saved as $filename");
                            }
                        }
                    } catch (Exception $e) {
                        error_log("Music download failed: " . $e->getMessage());
                    }
                }
                break;
        }
        
    } else {
        // Task failed
        error_log("Music extension 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");
        }
    }

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

## Best Practices

<Tip>
  ### Music Extension Callback Configuration

  1. **Source Validation**: Verify that the original audio source is valid before processing extension callbacks
  2. **Duration Tracking**: Monitor the extended duration to ensure it meets your requirements
  3. **Quality Check**: Implement quality checks for the extended audio segments
  4. **Version Control**: Keep track of extension iterations and maintain version history
  5. **Fallback Handling**: Implement fallback mechanisms if extension fails
  6. **Seamless Integration**: Ensure the extended portion integrates smoothly with the original track
</Tip>

<Warning>
  ### Extension-Specific Considerations

  * Extension tasks require a valid source audio file
  * The `continueAt` parameter determines where the extension begins
  * Extended tracks maintain the style and characteristics of the original
  * Extension quality depends on the source audio quality
  * Some complex musical structures may be challenging to extend seamlessly
</Warning>

## Troubleshooting

Common issues specific to music extension callbacks:

<AccordionGroup>
  <Accordion title="Extension Quality Issues">
    * Verify the source audio quality and format
    * Check if the `continueAt` parameter is set to an appropriate time point
    * Ensure the extension prompt matches the original music style
    * Consider the musical complexity of the source material
  </Accordion>

  <Accordion title="Source Audio Problems">
    * Confirm the source audio ID is valid and accessible
    * Verify the original audio file is not corrupted
    * Check if the source audio meets minimum quality requirements
    * Ensure the original track has sufficient content for extension
  </Accordion>

  <Accordion title="Timing and Synchronization">
    * Verify the `continueAt` timestamp is within the valid range
    * Check for audio synchronization issues in the extended portion
    * Monitor for tempo or key changes that might affect extension quality
  </Accordion>
</AccordionGroup>

## Alternative Solutions

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

<Card title="Poll Extension Results" icon="radar" href="/suno-api/get-music-generation-details">
  Use the Get Music Generation Details interface to regularly query extension task status. Recommend querying every 30 seconds.
</Card>
