HttpListener返回音频文件,以便在浏览器上播放

时间:2017-03-24 15:44:31

标签: c# http webserver httplistener

我正在使用HttpListener类来创建一个非常简单的Web服务器。

我能够为浏览器提供html,javascript,附件。 我唯一遇到的麻烦就是给浏览器一个wav文件以便播放它。

我想在浏览器中播放的文件是这样的: https://dl.dropboxusercontent.com/u/81397375/a.wav

请注意,如果您点击该链接,您的浏览器将开始播放音频文件,而不是将其作为附件下载。我想用HttpListerner类做同样的事情!

无论如何,这是我的代码:

Ext.define('MyApp.view.main.MainModel', {
    extend: 'Ext.app.ViewModel',

    alias: 'viewmodel.main',

    data: {
        selectedGroup: null
    },

    stores: {
        users: {
            model: 'User',
            fields: [
                'name', 'email', 'phone'
            ],
            proxy: {
                type: 'ajax',
                url: 'resources/users.json',
                reader: {
                    type: 'json',
                    rootProperty: 'users'
                },
                extraParams: {
                    myParam: '{selectedGroup.id}'
                }
            },
            updateProxy: function (proxy) {
                proxy.onAfter('extraparamschanged', this.load, this)
            }
        },
        groups: {
            type: 'tree',
            root: {
                expanded: true,
                children: [
                    {text: 'group1', leaf: true},
                    {
                        text: 'group2', expanded: true, children: [
                        {text: 'subgroup1', leaf: true},
                        {text: 'subgroup2', leaf: true}
                    ]
                    },
                    {text: 'group3', leaf: true}
                ]
            }
        }
    }
});


Ext.define('MyApp.view.main.Main', {
    extend: 'Ext.container.Container',
    xtype: 'app-main',

    requires: [
        'Ext.plugin.Viewport',
        'MyApp.view.main.MainModel'
    ],

    viewModel: 'main',

    layout: 'hbox',

    items: [{
        xtype: 'treepanel',
        title: 'Groups Tree',
        bind: {
            selection: '{selectedGroup}',
            store: '{groups}'
        },
        flex: 1
    }, {
        xtype: 'grid',
        title: 'Users',
        bind: '{users}',
        columns: [{
            text: 'Name',
            dataIndex: 'name',
            flex: 1
        }, {
            text: 'Company',
            dataIndex: 'company',
            flex: 1
        }, {
            text: 'Email',
            dataIndex: 'email',
            flex: 1
        }, {
            text: 'Phone',
            dataIndex: 'phone',
            flex: 1
        }],
        flex: 1
    }]
});

现在,当我去string pathToMyAudioFile = @"c:\a.wav"; // create web server var web = new HttpListener(); // listen on port 8081 only on local connections for testing purposes web.Prefixes.Add("http://localhost:8081/"); Console.WriteLine(@"Listening..."); web.Start(); // run web server forever while (true) { var context = web.GetContext(); var requestUrl = context.Request.Url.LocalPath.Trim('/'); // this command will stop the web server if (requestUrl == "Stop") { context.Response.StatusCode = 200; // set response to ok context.Response.OutputStream.Close(); break; } else if (requestUrl == "DownloadAudio") // <--------- here is where I am interested { // we are ready to give audio file to browser using (var fs = new FileStream(pathToMyAudioFile , FileMode.Open)) { context.Response.ContentLength64 = fs.Length; context.Response.SendChunked = true; //obj.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet; context.Response.ContentType = "audio/wav"; //obj.Response.AddHeader("Content-disposition", "attachment; filename=" + fs.Name); context.Response.StatusCode = 206; // set to partial content byte[] buffer = new byte[64 * 1024]; try { using (BinaryWriter bw = new BinaryWriter(context.Response.OutputStream)) { int read; while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, read); bw.Flush(); //seems to have no effect } bw.Close(); } } catch { Console.Write("closded connection"); } } } else { context.Response.StatusCode = 404; // set response to not found } // close output stream context.Response.OutputStream.Close(); } web.Stop(); 时,我看到了这一点:

enter image description here

但我无法播放该文件。为什么?我错过了哪些标题?我不想将文件作为附件下载。

解决方案

我刚刚找到了解决方案。我错过了http://localhost:8081/DownloadAudio标题。这就是当它再次成为真正的Web服务器IIS时的响应:

enter image description here

请注意它如何使用标题指定它发送的范围:Content-Range

所以我只需要添加一行

Content-Range: bytes 0-491515/491516

到我的代码,现在它的工作原理!如果音频文件非常大,我可以做一些数学运算,所以我不会立刻返回所有内容。

0 个答案:

没有答案