File size: 13,123 Bytes
fe29394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a90f04
fe29394
 
 
886e8be
6e3d789
 
 
 
 
886e8be
 
fe29394
 
6e3d789
 
 
 
 
886e8be
6e3d789
 
 
 
 
 
 
 
 
 
 
 
 
 
fe29394
6e3d789
 
 
 
 
 
fe29394
 
886e8be
fe29394
 
886e8be
6e3d789
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886e8be
 
6e3d789
 
 
 
 
 
fe29394
6e3d789
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886e8be
fe29394
 
 
 
 
 
 
 
6e3d789
 
 
fe29394
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
document.addEventListener('DOMContentLoaded', () => {
    // DOM Elements
    const uploadBtn = document.getElementById('upload-btn');
    const audioUpload = document.getElementById('audio-upload');
    const audioControls = document.getElementById('audio-controls');
    const songTitle = document.getElementById('song-title');
    const songDuration = document.getElementById('song-duration');
    const currentTimeEl = document.getElementById('current-time');
    const totalTimeEl = document.getElementById('total-time');
    const playBtn = document.getElementById('play-btn');
    const visualPreview = document.getElementById('visual-preview');
    const styleOptions = document.getElementById('style-options');
    const renderSection = document.getElementById('render-section');
    const generateBtn = document.getElementById('generate-btn');
    const progressContainer = document.getElementById('progress-container');
    const progressBar = document.getElementById('progress-bar');
    const progressPercent = document.getElementById('progress-percent');
    const downloadSection = document.getElementById('download-section');
    const downloadBtn = document.getElementById('download-btn');
    const visualizerCanvas = document.getElementById('visualizer');
    const videoCanvas = document.getElementById('video-canvas');
    
    // Audio context and variables
    let audioContext;
    let analyser;
    let audioBuffer;
    let audioElement;
    let wavesurfer;
    let isPlaying = false;
    let selectedStyle = 'abstract';
    let animationId;
    
    // Initialize Wavesurfer
    function initWavesurfer() {
        wavesurfer = WaveSurfer.create({
            container: '#waveform',
            waveColor: '#8B5CF6',
            progressColor: '#EC4899',
            cursorColor: '#EC4899',
            barWidth: 2,
            barRadius: 3,
            cursorWidth: 1,
            height: 60,
            barGap: 2,
            responsive: true,
        });
        
        wavesurfer.on('ready', () => {
            audioElement = wavesurfer.backend.getAudioElement();
            setupAudioAnalysis();
            updateDuration();
            playBtn.innerHTML = '<i data-feather="play" class="w-5 h-5"></i>';
            feather.replace();
        });
        
        wavesurfer.on('audioprocess', updateCurrentTime);
        wavesurfer.on('seek', updateCurrentTime);
        wavesurfer.on('finish', () => {
            isPlaying = false;
            playBtn.innerHTML = '<i data-feather="play" class="w-5 h-5"></i>';
            feather.replace();
        });
    }
    
    // Setup audio analysis
    function setupAudioAnalysis() {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioContext.createAnalyser();
        analyser.fftSize = 256;
        
        const source = audioContext.createMediaElementSource(audioElement);
        source.connect(analyser);
        analyser.connect(audioContext.destination);
        
        startVisualizer();
    }
    
    // Audio visualizer
    function startVisualizer() {
        const canvasCtx = visualizerCanvas.getContext('2d');
        const WIDTH = visualizerCanvas.width = visualizerCanvas.offsetWidth;
        const HEIGHT = visualizerCanvas.height = visualizerCanvas.offsetHeight;
        
        const bufferLength = analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);
        
        function draw() {
            animationId = requestAnimationFrame(draw);
            
            analyser.getByteFrequencyData(dataArray);
            
            canvasCtx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
            
            const barWidth = (WIDTH / bufferLength) * 2.5;
            let x = 0;
            
            for (let i = 0; i < bufferLength; i++) {
                const barHeight = (dataArray[i] / 255) * HEIGHT;
                const hue = i / bufferLength * 360;
                
                canvasCtx.fillStyle = `hsla(${hue}, 100%, 50%, 0.8)`;
                canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
                
                x += barWidth + 1;
            }
        }
        
        draw();
    }
    
    // Update current time display
    function updateCurrentTime() {
        if (audioElement) {
            const currentTime = formatTime(audioElement.currentTime);
            currentTimeEl.textContent = currentTime;
        }
    }
    
    // Update duration display
    function updateDuration() {
        if (audioElement) {
            const duration = formatTime(audioElement.duration);
            totalTimeEl.textContent = duration;
            songDuration.textContent = duration;
        }
    }
    
    // Format time (seconds to MM:SS)
    function formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    }
    
    // Generate background image based on audio analysis
    function generateBackgroundImage(style) {
        // In a real app, this would use the audio analysis to generate an image
        // For demo purposes, we'll use placeholder gradients based on style
        
        let gradient;
        switch (style) {
            case 'nature':
                gradient = 'linear-gradient(135deg, #10B981 0%, #3B82F6 100%)';
                break;
            case 'cosmic':
                gradient = 'linear-gradient(135deg, #8B5CF6 0%, #EC4899 100%)';
                break;
            default: // abstract
                gradient = 'linear-gradient(135deg, #6366F1 0%, #A78BFA 50%, #F472B6 100%)';
        }
        
        visualPreview.style.backgroundImage = gradient;
    }
    
    // Event listeners
    uploadBtn.addEventListener('click', () => audioUpload.click());
    
    audioUpload.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        songTitle.textContent = file.name.replace('.mp3', '');
        
        // Initialize wavesurfer if not already done
        if (!wavesurfer) {
            initWavesurfer();
        }
        
        const blobUrl = URL.createObjectURL(file);
        wavesurfer.load(blobUrl);
        
        audioControls.classList.remove('hidden');
        styleOptions.classList.remove('hidden');
        renderSection.classList.remove('hidden');
        downloadSection.classList.add('hidden');
        
        // Generate initial background
        generateBackgroundImage(selectedStyle);
    });
    
    playBtn.addEventListener('click', () => {
        if (!wavesurfer) return;
        
        if (isPlaying) {
            wavesurfer.pause();
            isPlaying = false;
            playBtn.innerHTML = '<i data-feather="play" class="w-5 h-5"></i>';
        } else {
            wavesurfer.play();
            isPlaying = true;
            playBtn.innerHTML = '<i data-feather="pause" class="w-5 h-5"></i>';
        }
        feather.replace();
    });
    
    // Style selection
    document.querySelectorAll('.style-option').forEach(btn => {
        btn.addEventListener('click', () => {
            selectedStyle = btn.dataset.style;
            document.querySelectorAll('.style-option').forEach(b => {
                b.classList.remove('border-purple-500', 'border-2');
            });
            btn.classList.add('border-purple-500', 'border-2');
            generateBackgroundImage(selectedStyle);
        });
    });
    // Generate video
    generateBtn.addEventListener('click', async () => {
        if (!wavesurfer || wavesurfer.isLoading()) {
            alert('Please wait for the audio to finish loading first');
            return;
        }

        // Reset visualizer if already running
        if (animationId) {
            cancelAnimationFrame(animationId);
        }

        generateBtn.disabled = true;
        generateBtn.innerHTML = '<span class="animate-pulse">Generating...</span>';
        progressContainer.classList.remove('hidden');
        
        // Setup video canvas
        videoCanvas.width = 1280;
        videoCanvas.height = 720;
        const videoCtx = videoCanvas.getContext('2d');
        videoCanvas.classList.remove('hidden');

        // Create a MediaRecorder to capture the visualization
        const stream = videoCanvas.captureStream(30);
        const mediaRecorder = new MediaRecorder(stream, {
            mimeType: 'video/webm;codecs=vp9'
        });

        const chunks = [];
        mediaRecorder.ondataavailable = (event) => {
            chunks.push(event.data);
        };

        mediaRecorder.onstop = () => {
            const blob = new Blob(chunks, { type: 'video/webm' });
            const url = URL.createObjectURL(blob);
            
            // Convert to MP4 (simulated)
            setTimeout(() => {
                progressBar.style.width = '100%';
                progressPercent.textContent = '100%';
                progressPercent.previousElementSibling.textContent = 'Finalizing...';
                
                setTimeout(() => {
                    generateBtn.disabled = false;
                    generateBtn.innerHTML = 'Generate Video';
                    progressContainer.classList.add('hidden');
                    downloadSection.classList.remove('hidden');
                    
                    downloadBtn.href = url;
                    downloadBtn.download = `${songTitle.textContent || 'audio-visualization'}.mp4`;
                }, 500);
            }, 1000);
        };

        // Start recording
        mediaRecorder.start(100); // Collect data every 100ms

        // Animation frame for video generation
        let startTime = Date.now();
        const duration = wavesurfer.getDuration() * 1000;
        let lastFrameTime = 0;
        const frameRate = 30;
        const frameInterval = 1000 / frameRate;

        function renderVideoFrame() {
            const currentTime = Date.now() - startTime;
            const progress = Math.min(100, (currentTime / duration) * 100);
            
            progressBar.style.width = `${progress}%`;
            progressPercent.textContent = `${Math.round(progress)}%`;
            progressPercent.previousElementSibling.textContent = 'Rendering...';

            // Update visualization
            const analyserData = new Uint8Array(analyser.frequencyBinCount);
            analyser.getByteFrequencyData(analyserData);

            // Draw visualization
            videoCtx.fillStyle = 'rgba(0, 0, 0, 1)';
            videoCtx.fillRect(0, 0, videoCanvas.width, videoCanvas.height);

            // Create gradient based on selected style
            let gradient;
            switch(selectedStyle) {
                case 'nature':
                    gradient = videoCtx.createLinearGradient(0, 0, videoCanvas.width, videoCanvas.height);
                    gradient.addColorStop(0, '#10B981');
                    gradient.addColorStop(1, '#3B82F6');
                    break;
                case 'cosmic':
                    gradient = videoCtx.createLinearGradient(0, 0, videoCanvas.width, videoCanvas.height);
                    gradient.addColorStop(0, '#8B5CF6');
                    gradient.addColorStop(1, '#EC4899');
                    break;
                default: // abstract
                    gradient = videoCtx.createLinearGradient(0, 0, videoCanvas.width, videoCanvas.height);
                    gradient.addColorStop(0, '#6366F1');
                    gradient.addColorStop(0.5, '#A78BFA');
                    gradient.addColorStop(1, '#F472B6');
            }

            // Draw bars based on audio data
            const barWidth = videoCanvas.width / analyserData.length;
            for (let i = 0; i < analyserData.length; i++) {
                const barHeight = (analyserData[i] / 255) * videoCanvas.height;
                videoCtx.fillStyle = gradient;
                videoCtx.fillRect(i * barWidth, videoCanvas.height - barHeight, barWidth, barHeight);
            }

            // Add song title
            videoCtx.fillStyle = 'white';
            videoCtx.font = 'bold 48px Poppins';
            videoCtx.textAlign = 'center';
            videoCtx.fillText(songTitle.textContent || 'Audio Visualization', videoCanvas.width/2, videoCanvas.height/2);

            if (currentTime < duration) {
                animationId = requestAnimationFrame(renderVideoFrame);
            } else {
                mediaRecorder.stop();
            }
        }

        // Start the visualization
        renderVideoFrame();
});
    // Clean up on unmount
    window.addEventListener('beforeunload', () => {
        if (animationId) {
            cancelAnimationFrame(animationId);
        }
        if (audioContext && audioContext.state !== 'closed') {
            audioContext.close();
        }
        // Clean up any media streams
        const streams = videoCanvas.captureStream().getTracks();
        streams.forEach(stream => stream.stop());
    });
});