搜尋此網誌

2009年12月29日 星期二

Silverlight:Web Load Media

建立一個Button物件,按下後能動態載入影片檔案。這樣的動作可以運用於「需要時才載入」,避免Silverlight的xap檔案過大導致載入時間過長。

在撰寫程式之前,請先新增一個新的專案到目前的solution中,並且將影象檔案置入該新增的專案:

新增專案至Solution,本篇將新增的專案命名為「VedioPack」

將影片檔加入專案中,在此以「_Butterfly_Small.wmv」為例:


在 .xmal檔中加入以下程式碼:

<Grid x:Name="LayoutRoot">
 <Button Width="100" Height="30" Content="load vedio" VerticalAlignment="Top"
Click="loadVedio" />
  <MediaElement Height="180" VerticalAlignment="Center" Width="240"
   d:LayoutOverrides="Width" HorizontalAlignment="Stretch"
   Volume="1" x:Name="vedio" Stretch="Uniform"/>
 <TextBlock x:Name="progressText" Text="%" Margin="-100,0"
  HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>


上述程式碼中,TextBlock元件將會顯示目前Media檔案的下載進度。接著在 .cs 檔案加入以下程式內容:

當按鈕被Click時:

private void loadVedio(object sender, RoutedEventArgs e)
{
  WebClient wc = new WebClient();
  wc.DownloadProgressChanged +=
  new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
  wc.OpenReadCompleted +=
  new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
  wc.OpenReadAsync(new Uri("ClientBin/VedioPack.xap", UriKind.Relative));
}

下載中,檔案下載進度的反應:

void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressText.Text = e.ProgressPercentage.ToString() + "%";
}

下載檔案的結果:

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  if ((e.Error == null) && (e.Cancelled == false))
  {
   try
   {
    StreamResourceInfo sri =
      new StreamResourceInfo(e.Result as Stream, null);
    Uri uri =
      new Uri("_Butterfly_Small.wmv", UriKind.Relative);
    StreamResourceInfo mediaStream = Application.GetResourceStream(sri, uri);
    this.vedio.SetSource(mediaStream.Stream);
    progressText.Visibility = Visibility.Collapsed;
   }
   catch(Exception ex)
   {
    System.Windows.Browser.HtmlPage.Window.Alert(ex.Message);
   }
  }
  else
  {
   MessageBox.Show(e.Error.ToString());
  }
}


執行結果

沒有留言:

張貼留言