P
P
Petr Ponomarev2019-03-22 11:47:08
JavaScript
Petr Ponomarev, 2019-03-22 11:47:08

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])

The important thing is that the problem seems to be in the player itself, because it waits for part of the file to be downloaded and only then starts playing

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MikeMoore, 2019-03-22
@MikeMoore

To solve the problem - you need to see the code

F
falconandy, 2019-03-23
@falconandy

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 question

Ask a Question

731 491 924 answers to any question