Integrações
JavaScript Puro
Construa experiências de gravação de vídeo personalizadas com o Core SDK do VIDTREO.
JavaScript Vanilla
O pacote @vidtreo/recorder fornece o Core SDK para construir experiências de gravação de vídeo completamente personalizadas.
Instalação
npm install @vidtreo/recorderUso Básico
import { VidtreoRecorder } from '@vidtreo/recorder';
// Inicializar o gravador
const recorder = new VidtreoRecorder({
apiKey: 'sua-api-key',
onUploadComplete: (result) => {
console.log('URL do Vídeo:', result.uploadUrl);
},
onError: (error) => {
console.error('Erro:', error);
}
});
// Inicializar e começar preview
await recorder.initialize();
const stream = await recorder.startPreview();
// Conectar ao elemento vídeo
const video = document.querySelector('video');
video.srcObject = stream;
// Iniciar gravação
await recorder.startRecording();
// Parar e enviar
const result = await recorder.stopRecording();
console.log('Gravação completa:', result);Opções de Configuração
interface VidtreoRecorderConfig {
// Obrigatório
apiKey: string;
// Opcional
apiUrl?: string; // Padrão: 'https://core.vidtreo.com'
enableSourceSwitching?: boolean; // Padrão: true
enableMute?: boolean; // Padrão: true
enablePause?: boolean; // Padrão: true
enableDeviceChange?: boolean; // Padrão: true
maxRecordingTime?: number; // Duração máxima em ms
countdownDuration?: number; // Contagem regressiva em ms
userMetadata?: Record<string, unknown>; // Metadados personalizados
enableTabVisibilityOverlay?: boolean; // Mostrar overlay ao ocultar aba
tabVisibilityOverlayText?: string; // Texto do overlay personalizado
// Callbacks
onUploadComplete?: (result: UploadResult) => void;
onUploadProgress?: (progress: number) => void;
onUploadError?: (error: Error) => void;
onRecordingStart?: () => void;
onRecordingStop?: () => void;
onError?: (error: Error) => void;
}Métodos Principais
Inicialização
// Inicializar o gravador
await recorder.initialize();Preview
// Iniciar preview da câmera
const stream = await recorder.startPreview('camera');
// Iniciar preview da tela
const stream = await recorder.startPreview('screen');Gravação
// Iniciar gravação com opções
await recorder.startRecording({
video: {
width: 1920,
height: 1080,
frameRate: 30
},
audio: true
}, 'camera'); // ou 'screen'
// Parar gravação
const result = await recorder.stopRecording();
// result: { recordingId, uploadUrl, blob }Controle de Áudio
// Silenciar áudio
recorder.muteAudio();
// Ativar áudio
recorder.unmuteAudio();
// Alternar mudo
recorder.toggleMute();
// Verificar estado de mudo
const isMuted = recorder.isMuted();Pausar/Retomar
// Pausar gravação
recorder.pauseRecording();
// Retomar gravação
recorder.resumeRecording();
// Verificar estado de pausa
const isPaused = recorder.isPaused();Troca de Fonte
// Mudar para gravação de tela
await recorder.switchSource('screen');
// Voltar para câmera
await recorder.switchSource('camera');Gerenciamento de Dispositivos
// Obter dispositivos disponíveis
const devices = await recorder.getAvailableDevices();
// devices: { video: MediaDeviceInfo[], audio: MediaDeviceInfo[] }Estado
// Obter estado atual de gravação
const state = recorder.getRecordingState();
// state: 'idle' | 'countdown' | 'recording'
// Obter stream atual
const stream = recorder.getStream();Limpeza
// Limpar recursos
recorder.cleanup();Exemplo Completo
import { VidtreoRecorder } from '@vidtreo/recorder';
class VideoRecorderApp {
private recorder: VidtreoRecorder;
private videoElement: HTMLVideoElement;
private recordButton: HTMLButtonElement;
private stopButton: HTMLButtonElement;
private muteButton: HTMLButtonElement;
constructor() {
this.videoElement = document.getElementById('preview') as HTMLVideoElement;
this.recordButton = document.getElementById('record') as HTMLButtonElement;
this.stopButton = document.getElementById('stop') as HTMLButtonElement;
this.muteButton = document.getElementById('mute') as HTMLButtonElement;
this.recorder = new VidtreoRecorder({
apiKey: 'sua-api-key',
maxRecordingTime: 300000, // 5 minutos
countdownDuration: 3000,
userMetadata: {
userId: 'user-123'
},
onRecordingStart: () => {
this.updateUI('recording');
},
onRecordingStop: () => {
this.updateUI('processing');
},
onUploadProgress: (progress) => {
this.showProgress(progress);
},
onUploadComplete: (result) => {
this.showResult(result);
},
onError: (error) => {
this.showError(error);
}
});
this.bindEvents();
this.init();
}
async init() {
await this.recorder.initialize();
const stream = await this.recorder.startPreview();
this.videoElement.srcObject = stream;
this.updateUI('ready');
}
bindEvents() {
this.recordButton.addEventListener('click', () => this.startRecording());
this.stopButton.addEventListener('click', () => this.stopRecording());
this.muteButton.addEventListener('click', () => this.toggleMute());
}
async startRecording() {
await this.recorder.startRecording();
}
async stopRecording() {
await this.recorder.stopRecording();
}
toggleMute() {
this.recorder.toggleMute();
this.muteButton.textContent = this.recorder.isMuted() ? 'Ativar Áudio' : 'Silenciar';
}
updateUI(state: string) {
// Atualizar UI baseado no estado
this.recordButton.disabled = state !== 'ready';
this.stopButton.disabled = state !== 'recording';
}
showProgress(progress: number) {
console.log(`Upload: ${Math.round(progress * 100)}%`);
}
showResult(result: { uploadUrl: string; recordingId: string }) {
console.log('Vídeo pronto:', result.uploadUrl);
}
showError(error: Error) {
console.error('Erro:', error);
}
}
// Inicializar quando o DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
new VideoRecorderApp();
});Template HTML
<!DOCTYPE html>
<html>
<head>
<title>Gravador de Vídeo</title>
<style>
.recorder {
max-width: 640px;
margin: 0 auto;
}
video {
width: 100%;
background: #000;
border-radius: 8px;
}
.controls {
margin-top: 1rem;
display: flex;
gap: 0.5rem;
}
button {
padding: 0.5rem 1rem;
border-radius: 4px;
border: none;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
</head>
<body>
<div class="recorder">
<video id="preview" autoplay muted playsinline></video>
<div class="controls">
<button id="record">Gravar</button>
<button id="stop" disabled>Parar</button>
<button id="mute">Silenciar</button>
</div>
</div>
<script type="module" src="./recorder.ts"></script>
</body>
</html>Avançado: Usando Módulos Individuais
Para máximo controle, importe módulos individuais:
import {
RecorderController,
DeviceManager,
AudioLevelAnalyzer,
UploadService,
StorageManager,
VideoTranscoder
} from '@vidtreo/recorder';
// Gerenciamento de dispositivos
const deviceManager = new DeviceManager();
const devices = await deviceManager.enumerateDevices();
// Visualização de áudio
const analyzer = new AudioLevelAnalyzer(audioTrack);
analyzer.start((level) => {
// level: 0-1
updateAudioMeter(level);
});
// Transcodificação manual
const transcoder = new VideoTranscoder();
const mp4Blob = await transcoder.transcode(webmBlob, {
format: 'mp4',
fps: 30,
width: 1920,
height: 1080
});
// Upload personalizado
const uploadService = new UploadService({
apiKey: 'sua-api-key',
apiUrl: 'https://core.vidtreo.com'
});
const result = await uploadService.upload(mp4Blob, {
onProgress: (progress) => console.log(progress)
});Definições de Tipos
// Estados de gravação
type RecordingState = 'idle' | 'countdown' | 'recording';
type SourceType = 'camera' | 'screen';
// Resultado de gravação
interface RecordingStopResult {
recordingId: string;
uploadUrl: string;
blob: Blob;
}
// Info de dispositivos
interface AvailableDevices {
video: MediaDeviceInfo[];
audio: MediaDeviceInfo[];
}
// Opções de gravação
interface RecordingStartOptions {
video?: {
width?: number;
height?: number;
frameRate?: number;
};
audio?: boolean | MediaTrackConstraints;
}O Core SDK é a base para os pacotes React e Web Component. Todos os recursos disponíveis nos pacotes wrapper são construídos sobre estas APIs.
Próximos Passos
- Referência de API — Documentação completa da API
- Referência de Tipos — Todos os tipos TypeScript
- Exemplo de UI Personalizada — Construa interfaces personalizadas