Can listen to tracks in the browser

This commit is contained in:
nemunaire 2022-10-15 13:29:25 +02:00
parent 69ddfd48e9
commit 2bcac6edd1
3 changed files with 52 additions and 0 deletions

View File

@ -85,6 +85,24 @@ func declareTracksRoutes(cfg *config.Config, router *gin.RouterGroup) {
tracksRoutes.GET("", func(c *gin.Context) {
c.JSON(http.StatusOK, c.MustGet("track"))
})
tracksRoutes.GET("/stream", func(c *gin.Context) {
track := c.MustGet("track").(*reveil.Track)
size, err := track.Size()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to open the track: %s", err.Error())})
return
}
fd, err := track.Open()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to open the track: %s", err.Error())})
return
}
defer fd.Close()
c.DataFromReader(http.StatusOK, size, track.ContentType(), fd, map[string]string{})
})
tracksRoutes.PUT("", func(c *gin.Context) {
oldtrack := c.MustGet("track").(*reveil.Track)

View File

@ -46,6 +46,33 @@ func LoadTracks(cfg *config.Config) (tracks []*Track, err error) {
return
}
func (t *Track) Open() (*os.File, error) {
return os.Open(t.Path)
}
func (t *Track) Size() (int64, error) {
if st, err := os.Stat(t.Path); err != nil {
return 0, err
} else {
return st.Size(), err
}
}
func (t *Track) ContentType() string {
switch filepath.Ext(t.Path) {
case ".flac":
return "audio/flac"
case ".mp3":
return "audio/mpeg"
case ".ogg":
return "audio/ogg"
case ".wav":
return "audio/vnd.wav"
}
return "application/octet-stream"
}
func (t *Track) Rename(newName string) error {
newPath := filepath.Join(filepath.Dir(t.Path), newName+filepath.Ext(t.Path))

View File

@ -52,6 +52,13 @@
</ListGroupItem>
</ListGroup>
<div class="my-2 d-flex justify-content-center">
<audio controls class="w-100 rounded">
<source src="api/tracks/{track.id}/stream">
Your browser does not support the audio element.
</audio>
</div>
<ListGroup class="my-2 text-center">
<ListGroupItem
action