> ## 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 Video Generation Callbacks

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

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

* Music video generation completed
* Music video generation task failed
* Error occurred during task processing

<Note>
  Music video generation has only one callback stage, providing the MP4 video 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 Video Generation Complete Callback theme={null}
  {
    "code": 200,
    "msg": "MP4 generated successfully.",
    "data": {
      "task_id": "taskId_774b9aa0422f",
      "video_url": "https://example.com/videos/video_847715e66259.mp4"
    }
  }
  ```

  ```json Video Generation Failed Callback theme={null}
  {
    "code": 400,
    "msg": "Video generation failed, invalid source audio",
    "data": {
      "task_id": "taskId_774b9aa0422f",
      "video_url": null
    }
  }
  ```
</CodeGroup>

## Status Code Description

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

  | Status Code | Description                                                |
  | ----------- | ---------------------------------------------------------- |
  | 200         | Success - Music video generation 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.video_url" type="string">
  Generated MP4 video 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('/video-callback', (req, res) => {
      const { code, msg, data } = req.body;
      
      console.log('Received music video callback:', {
        taskId: data.task_id,
        status: code,
        message: msg
      });
      
      if (code === 200 && data.video_url) {
        // Video generation successful
        console.log(`Music video ready: ${data.video_url}`);
        
        // Download video file
        downloadVideoFile(data.video_url, data.task_id);
        
      } else {
        // Task failed
        console.log('Music video generation 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 downloadVideoFile(url, taskId) {
      const filename = `video_${taskId}.mp4`;
      const file = fs.createWriteStream(filename);
      
      https.get(url, (response) => {
        response.pipe(file);
        
        file.on('finish', () => {
          file.close();
          console.log(`Video file downloaded: ${filename}`);
        });
      }).on('error', (err) => {
        console.error('Video download failed:', err.message);
      });
    }

    app.listen(3000, () => {
      console.log('Video 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('/video-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')
        video_url = callback_data.get('video_url')
        
        print(f"Received music video callback: {task_id}, Status: {code}")
        
        if code == 200 and video_url:
            # Video generation successful
            print(f"Music video ready: {video_url}")
            
            # Download video file
            download_video_file(video_url, task_id)
            
        else:
            # Task failed
            print(f"Music video generation 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_video_file(url, task_id):
        """Download video file from the provided URL"""
        try:
            response = requests.get(url, stream=True)
            if response.status_code == 200:
                filename = f"video_{task_id}.mp4"
                with open(filename, "wb") as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)
                print(f"Video file downloaded: {filename}")
            else:
                print(f"Failed to download video file: HTTP {response.status_code}")
        except Exception as e:
            print(f"Video 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'] ?? '';
    $videoUrl = $callbackData['video_url'] ?? '';

    error_log("Received music video callback: $taskId, Status: $code");

    if ($code === 200 && $videoUrl) {
        // Video generation successful
        error_log("Music video ready: $videoUrl");
        
        // Download video file
        downloadVideoFile($videoUrl, $taskId);
        
    } else {
        // Task failed
        error_log("Music video generation 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 downloadVideoFile($url, $taskId) {
        try {
            $context = stream_context_create([
                'http' => [
                    'timeout' => 300 // 5 minutes timeout for large video files
                ]
            ]);
            
            $videoContent = file_get_contents($url, false, $context);
            if ($videoContent !== false) {
                $filename = "video_{$taskId}.mp4";
                file_put_contents($filename, $videoContent);
                error_log("Video file downloaded: $filename");
            } else {
                error_log("Failed to download video file from URL");
            }
        } catch (Exception $e) {
            error_log("Video 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>
  ### Music Video Callback Configuration

  1. **File Size Management**: Prepare for larger file downloads as videos are significantly bigger than audio
  2. **Storage Planning**: Ensure adequate storage space for MP4 video files
  3. **Download Optimization**: Use streaming downloads for large video files to avoid memory issues
  4. **Quality Verification**: Verify video file integrity and playback after download
  5. **Metadata Handling**: Maintain video metadata and track association with original audio
  6. **Backup Strategy**: Implement backup procedures for generated video content
</Tip>

<Warning>
  ### Video-Specific Considerations

  * Video files are much larger than audio files, requiring more storage and bandwidth
  * Download times can be significantly longer depending on video length and quality
  * Ensure stable network connectivity for large file transfers
  * Video generation may take longer than audio processing
  * Consider implementing progress tracking for video downloads
  * Video URLs may have shorter expiration times due to storage costs
</Warning>

## Troubleshooting

Common issues specific to music video generation callbacks:

<AccordionGroup>
  <Accordion title="Download and Storage Issues">
    * Verify adequate storage space for video files
    * Check network stability for large file downloads
    * Implement chunked downloading for better reliability
    * Monitor download progress and implement retry mechanisms
  </Accordion>

  <Accordion title="Video Quality and Format">
    * Confirm the source audio quality meets video generation requirements
    * Verify that the generated MP4 plays correctly in different players
    * Check video resolution and quality settings
    * Test video compatibility across different devices and platforms
  </Accordion>

  <Accordion title="Performance Optimization">
    * Implement asynchronous video processing to avoid blocking
    * Consider background downloading for large video files
    * Monitor server resources during video processing
    * Plan for longer processing and download times compared to audio
  </Accordion>

  <Accordion title="Source Audio Requirements">
    * Ensure source audio meets minimum quality requirements
    * Verify that the audio ID and task ID are valid and accessible
    * Check if the source audio has sufficient content for video generation
    * Confirm that audio metadata is properly preserved in the video
  </Accordion>
</AccordionGroup>

## Alternative Solutions

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

<Card title="Poll Video Results" icon="radar" href="/suno-api/get-music-video-details">
  Use the Get Music Video Details interface to regularly query video generation task status. Recommend querying every 45 seconds due to longer processing times.
</Card>
