-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (62 loc) · 1.96 KB
/
main.go
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
package main
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
)
const (
tempDir = "temp" // Temporary directory for files
)
func karaokeHandler(w http.ResponseWriter, r *http.Request) {
// Get YouTube URL from query parameter
youtubeURL := r.URL.Query().Get("url")
if youtubeURL == "" {
http.Error(w, "Missing 'url' query parameter", http.StatusBadRequest)
return
}
// Create a unique filename for the output files
timestamp := time.Now().Unix()
outputWAV := filepath.Join(tempDir, fmt.Sprintf("output_%d.wav", timestamp))
outputMP3 := filepath.Join(tempDir, fmt.Sprintf("output_%d.mp3", timestamp))
// Call the Python script
cmd := exec.Command("python3", "karaoke_generator.py", youtubeURL, outputWAV, outputMP3)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
http.Error(w, fmt.Sprintf("Failed to generate karaoke: %v", err), http.StatusInternalServerError)
return
}
// Serve the generated MP3 file
mp3File, err := os.Open(outputMP3)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to open MP3 file: %v", err), http.StatusInternalServerError)
return
}
defer mp3File.Close()
w.Header().Set("Content-Type", "audio/mpeg")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filepath.Base(outputMP3)))
if _, err := io.Copy(w, mp3File); err != nil {
http.Error(w, fmt.Sprintf("Failed to send MP3 file: %v", err), http.StatusInternalServerError)
return
}
// Clean up temporary files
os.Remove(outputWAV)
os.Remove(outputMP3)
}
func main() {
// Create the temporary directory if it doesn't exist
if err := os.MkdirAll(tempDir, os.ModePerm); err != nil {
fmt.Printf("Failed to create temp directory: %v\n", err)
return
}
// Set up the HTTP server
http.HandleFunc("/karaoke", karaokeHandler)
fmt.Println("Server started at http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Printf("Failed to start server: %v\n", err)
}
}