Something went wrong. Try again.
a simple (and fast) soundcloud downloader
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127package downcloud
import ( "context" "encoding/json" "fmt" "math" "net/http" "time")
type WaveformRows struct { Top string Bottom string}
func CompressWaveform(samples []float64, targetWidth int) []float64 { n := len(samples) if n == 0 || targetWidth <= 0 { return nil } chunkSize := int(math.Ceil(float64(n) / float64(targetWidth))) if chunkSize <= 0 { chunkSize = 1 }
compressed := make([]float64, 0, targetWidth) for i := 0; i < n; i += chunkSize { var sum float64 end := i + chunkSize if end > n { end = n } for j := i; j < end; j++ { sum += samples[j] } compressed = append(compressed, sum/float64(end-i)) } return compressed}
func ClampIndex(value float64, max int) int { v := int(math.Floor(value)) if v < 0 { return 0 } if v > max { return max } return v}
type waveformResponse struct { Samples []float64 `json:"samples"`}
func FetchWaveformRows(ctx context.Context, url string, width int) (*WaveformRows, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", UserAgent)
client := &http.Client{Timeout: 10 * time.Second} res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close()
if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("waveform HTTP status %d", res.StatusCode) }
var data waveformResponse if err := json.NewDecoder(res.Body).Decode(&data); err != nil { return nil, err } if len(data.Samples) == 0 { return nil, fmt.Errorf("no waveform samples found") }
compressed := CompressWaveform(data.Samples, width) var maxVal float64 for _, v := range compressed { if v > maxVal { maxVal = v } } if maxVal <= 0 { maxVal = 1 }
topSet := []rune{' ', '▖', '▌'} botSet := []rune{' ', '▘', '▌'}
topChars := make([]rune, len(compressed)) botChars := make([]rune, len(compressed))
for i, v := range compressed { n := v / maxVal topIdx := ClampIndex(n*float64(len(topSet)), len(topSet)-1) botIdx := ClampIndex(n*float64(len(botSet)), len(botSet)-1) topChars[i] = topSet[topIdx] botChars[i] = botSet[botIdx] }
return &WaveformRows{ Top: string(topChars), Bottom: string(botChars), }, nil}
func PrintASCIIWaveform(waveformURL string) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel()
rows, err := FetchWaveformRows(ctx, waveformURL, WaveWidth) if err != nil || rows == nil { return }
fmt.Println() fmt.Println(rows.Top) fmt.Printf("%s\n\n", Dim(rows.Bottom))}