2014-07-05 195 views
1

我必須播放大文件(300MB +)以外的音頻部分。播放音頻文件的一部分

這是我的代碼:

// Media source is a local file. 
// datName = "sound.dat" 
// pointer = position in file 
// length = length of the part to play 

try 
{ 
    file = await StorageFile.GetFileFromApplicationUriAsync 
      (new Uri(@"ms-appx:///Data/" + datName)); 
    // Get the media source as a stream. 
    IRandomAccessStream stream = 
      await file.OpenAsync(FileAccessMode.Read); 
    stream.Seek((ulong)pointer); // This is working, position changes from 0 to pointer 
    stream.Size = (ulong)length; // Is not working, Size remains unchanged at total file size 
    media.SetSource(stream, file.ContentType); 
    media.Play(); 
} 
catch (Exception ex) 
{ 
    if (ex is FormatException || ex is ArgumentException) 
    { 
     //ShowFileErrorMsg(); 
    } 
} 

請注意,流求和大小的意見。該文件從位置0播放。

如何從指針播放聲音到指針+長度?

+0

只是一個想法 - 也許你可以設置[音頻的位置(http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.mediaelement.position)在它被加載之後,並且隨着定時器(以適當的間隔)開始它,這將停止播放。 – Romasz

+0

音頻部分是不同長度的單詞。我無法估計發言時間來設定一個計時器。 – thpitsch

回答

1

我已經通過使用二進制閱讀器解決了我的問題。我在字節緩衝區中讀取所需區域並將其轉換爲IRandomAccessStream。

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Data/" + fileName)); 
using (Stream stream = (await file.OpenReadAsync()).AsStreamForRead()) 
using (BinaryReader reader = new BinaryReader(stream)) 
{ 
    reader.BaseStream.Position = pointer; 
    byte[] buffer = reader.ReadBytes((int)length); 
    IRandomAccessStream nstream = new MemoryStream(buffer).AsRandomAccessStream(); 
    media.SetSource(nstream, ""); 
    media.Play(); 
} 

這個版本現在工作。