crazydiv
crazydiv

Reputation: 842

Stream audio from an authenticated url

I have a external server URL to which I pass credentials and and id to get the audio file like http://myexternalserver.com/?u=xxx&p=xxx&id=xxx

In order to avoid doing this from javascript and exposing the credentials to user, I was attempting to call the url from backend and stream it to the UI request(on my server)

using (Stream mystream = httpResponse2.GetResponseStream())
{
    using (BinaryReader reader = new BinaryReader(mystream))
    {
        int length = 2048;
        byte[] buffer = new byte[length];
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.BufferOutput = true;
        response.ContentType = "audio/wav";
        while((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
        {
            response.OutputStream.Write(buffer, 0, bytesRead);
        }
        response.End();
    }
}

Using this approach, I am successfully able to play the stream in an <audio> element.

Below are issues which I'm facing:

I'm also not quite sure if this is a correct/best approach, so suggestions on approach would also be very helpful.

Upvotes: 1

Views: 911

Answers (1)

Kolyunya
Kolyunya

Reputation: 6240

I was able to solve the issue.

What I did was I examined what my HTTP server responded to requests for regular mp3 files stored on the server statically. I noticed that the server was setting two headers which I missed. Those were Accept-Ranges: bytes and Content-Length: xxx.

When I set those headers all the issues from the question disappeared.

Hope this will help somebody.

Upvotes: 1

Related Questions