Search code examples
scalaplayframeworkakka-stream

Play is downloading a file instead of streaming it


I'm trying to create an API that takes a file from AWS S3 and sends it to a front end where it can be played. But when I test it in a browser, it just downloads the file. I need the file to be played.

My action:

def index() = Action { implicit request: Request[AnyContent] =>
  val songname: String = "song.mp3"
  val objStream = s3.client.getObject("music", songname).getObjectContent

  val dataContent: Source[ByteString, _] = StreamConverters.fromInputStream(() => objStream)

  Ok.chunked(dataContent).withHeaders(ACCEPT_RANGES -> "bytes", CONTENT_TYPE -> "Content-Type: audio/mp3")
}

Also, it ignores my content_type header:

[warn] a.a.ActorSystemImpl - Explicitly set HTTP header 'Content-Type: Content-Type: audio/mp3' is ignored, illegal RawHeader

What should I change?


Solution

  • Use as instead of withHeaders:

    def index() = Action { implicit request =>
      val songname = "song.mp3"
      val objStream = s3.client.getObject("music", songname).getObjectContent
    
      val dataContent: Source[ByteString, _] =
        StreamConverters.fromInputStream(() => objStream)
    
      Ok.chunked(dataContent).as("audio/mp3")
                           // ^
    }