Answer the question
In order to leave comments, you need to log in
Golang + html5 audio + ios, why does the track take a long time to load?
In general, the problem is this, I give the file for the audio tag, I registered all the headers, the server is in golang, the file starts loading during playback, and playback starts only after half the file is loaded, which is about 10 seconds. If you upload a file to soundcloud from there, it also waits for half of the file to be downloaded, but it loads 20mb from there in less than 1 second. in comparison, it loads 15 mb from the server in 10 seconds.
1. Is it possible to somehow reduce the audio playback threshold for the tag
2. Perhaps soundcloud somehow simulates a file download and then uploads it?
name := strings.Replace(r.URL.Path, "/audio/", "", 1)
path := Helper.GetPathByName(name[0 : len(name)-4])
buf := bytes.NewBuffer(nil)
file, err := os.Open(path + name)
io.Copy(buf, file)
if err != nil {
Helper.JsonResponse(w, http.StatusForbidden, err.Error())
return
}
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Accept-Ranges","bytes")
w.Header().Set("Content-Type", "audio/mpeg")
file.Close()
fi := buf.Bytes()
rangeString := r.Header.Get("range")
start := 0
end := len(fi)
if rangeString == "" {
w.Header().Set("Content-Length", strconv.Itoa(len(buf.Bytes()[start:end])))
w.WriteHeader(200)
w.Write(fi[start:end])
return
}
str:=strings.Split(rangeString[len("bytes="):], "-")
if str[0] != "" {
start, err = strconv.Atoi(str[0])
}
if str[1] != "" {
end, err = strconv.Atoi(str[1])
}
strRange := Helper.ParseRangeToStr(int64(start), int64(end), int64(len(fi)))
w.Header().Set("Content-Range", strRange)
end += 1
contentLength := len(buf.Bytes()[start:end])
w.Header().Set("Content-Length", strconv.Itoa(contentLength))
w.WriteHeader(206)
w.Write(fi[start:end])
Answer the question
In order to leave comments, you need to log in
From the code, it looks like you are downloading the entire contents of the file on each request (io.Copy(buf, file)) - even if only part of the file is requested.
Do not reinvent the wheel - most likely, the http.ServeFile library function will do
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question