Home > front end >  Can I make the browser play an MP3 instead of downloading it?
Can I make the browser play an MP3 instead of downloading it?

Time:01-03

This is a bit tricky. I have a Minimal Web API with this function:

app
    .MapGet("/Speak/{name}/{*text}", (HttpContext context, string name, string text) =>
    {
        string mp3Name = $"{name} {DateTime.Now:yyyyMMdd HHmmss}.mp3";
        string filename= Path.Combine(Environment.CurrentDirectory, "Sounds", mp3Name);
        VoiceProfiles.GetVoices.Find(name).Speak(filename, bearerKey, text).Wait();
        return File(filename, "audio/mp3", mp3Name);
    });

This is nice and it downloads the MP3 file that is generated when I go to https://localhost:44305/speak/fanny/Hello, World. but that's not what I want. When I open that link in the browser, I want it to play the file instead!
Is that possible? Keep in mind there's no front-end here, just this URL that returns an MP3 file.


Solved, thanks to Mitch Denny but not because of the 'inline' header. I used:

  • return File(filename, "audio/mp3", mp3Name); While I should have used:
  • return File(new FileStream(filename, FileMode.Open), "audio/mp3"); The difference is minor, but returning it as a stream allows the browser to retrieve it as a stream and thus play it back. Returning it as a file just dumps it as such, and basically forces the browser to download it instead.
    Oh, well... Something to remember. :)

CodePudding user response:

I was able to get this working with Edge (Chromium):

app.MapGet("/mp3", (HttpResponse response) => {
    var stream = new FileStream("sample-3s.mp3", FileMode.Open);
    return Results.File(stream, "audio/mp3");
});

Just don't provide the filename.

  • Related