如何在代码中设置视频标签的来源?

时间:2017-02-16 06:14:58

标签: c# asp.net html5 html5-video

我在ASPX文件中使用此代码:

 <video width="320" height="240" autoplay="autoplay">
    <source id="videoSrc" runat="server"  type="video/mp4"/>
    Your browser does not support the video tag.
 </video>

但当我在代码中使用此代码时:

protected void Page_Load(object sender, EventArgs e)
{
    videoSrc.Src= "UploadMovies/"+Request.QueryString["id"]+"/high.mp4";
}

并将我的网页称为 myPage.aspx?id=1 我在<source>上收到此错误:

  

基类包括字段&#39; videoSrc&#39;,但其类型(System.Web.UI.HtmlControls.HtmlSource)与控件类型不兼容(System.Web.UI.HtmlControls.HtmlGenericControl) )。

2 个答案:

答案 0 :(得分:1)

你可以在这里做些什么。

首先完全摆脱<source>并使用src属性。您需要使video成为服务器端控件,但这不会导致错误:

<video width="320" height="240" autoplay="autoplay" id="video" runat="server">
</video>

video.Attributes["src"] = "UploadMovies/"+Request.QueryString["id"]+"/high.mp4";

另一件事是有一个代码隐藏功能,它将为您提供视频链接:

<video width="320" height="240" autoplay="autoplay">
    <source type="video/mp4" src='<%= GetVideoLink() %>'/>
</video>

protected string GetVideoLink()
{
    return "UploadMovies/"+Request.QueryString["id"]+"/high.mp4";
}

在这里,您还可以使用参数并使用多个<source>标记来支持回退。

至于你所看到的错误,为什么会发生这种情况并不明显。 HtmlSource是source标记的正确控件类型,不清楚为什么ASP.NET决定将其视为通用的html控件。你可以试试this workaround

答案 1 :(得分:0)

不指定source属性可能会导致某些浏览器出现不兼容问题(例如:Safari。请参阅https://github.com/mediaelement/mediaelement/issues/486)。

但是,没什么大不了的。可以从服务器端创建Source内部标记:

// Assuming we have runat="server" video tag in the markup side, with ID=vid:
// We could cast it as HtmlGenericControl. e.g: in a ItemDataBound event of a Repeater

// Now create the source tag    
HtmlGenericControl source1 = new HtmlGenericControl("source");

source1.Attributes["src"] = "your_video_url";
source1.Attributes["type"] = "video/mp4";

// We can also add additional sources:
HtmlGenericControl source2 = new HtmlGenericControl("source");
source2.Attributes["src"] = "your_video_second_url";
source2.Attributes["type"] = "video/webm";

// Now add the sources as child controls of the video control
vid.Controls.Add(source1);
vid.Controls.Add(source2);
相关问题