0

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,%20World. 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. :)
Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149

1 Answers1

1

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.

Mitch Denny
  • 2,095
  • 13
  • 19
  • It works, but not for the reason you think. As it turns out, return File(filename, "audio/mp3", mp3Name); should be return File(new FileStream(filename, FileMode.Open), "audio/mp3"); as I need to return it as a stream, not a file. :) – Wim ten Brink Jan 03 '23 at 03:38
  • 1
    Hrm, strange I thought I tested that and it didn't work but trying it again it does. Updated answer :) – Mitch Denny Jan 03 '23 at 03:54