2014-07-13 24 views
0

我試圖從基於此答案WAV文件繪製的波形: https://stackoverflow.com/a/1215472/356635企圖拉攏波的形式,但沒有得出任何數據

不幸的是,它會產生一個大黑方每次。我正在努力研究這是爲什麼,有人能夠發現問題嗎? normalisedData中的所有值都介於-1 and +1之間。 test.wav文件是播放5秒鐘警報聲音的Windows wav文件。

這裏是我的代碼:

using System; 
using System.Drawing; 
using System.IO; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     const string rootDir = "C:\\inetpub\\wwwroot\\"; 
     if (File.Exists(rootDir + "test.png")) 
     { 
      File.Delete(rootDir + "test.png"); 
     } 

     var stream = new MemoryStream(File.ReadAllBytes(rootDir + "test.wav")); 
     var data = stream.ToArray(); 
     stream.Dispose(); 
     var normalisedData = FloatArrayFromByteArray(data); 

     // Get max value in data 
     var maxValue = 0f; 
     for (var i = 0; i < normalisedData.Length; i++) 
     { 
      if (normalisedData[i] > maxValue) maxValue = normalisedData[i]; 
     } 

     // Normalise data 
     for (var i = 0; i < normalisedData.Length; i++) 
     { 
      normalisedData[i] = (data[i]/maxValue) * 100f; 
     }  

     // Save picture 
     var picture = DrawNormalizedAudio(normalisedData, Color.LimeGreen); 
     picture.Save(rootDir + "test.png", System.Drawing.Imaging.ImageFormat.Png); 
     picture.Dispose(); 
    } 
    public static Bitmap DrawNormalizedAudio(float[] data, Color color) 
    { 
     Bitmap bmp; 
     bmp = new Bitmap(500,500); 

     int BORDER_WIDTH = 5; 
     int width = bmp.Width - (2 * BORDER_WIDTH); 
     int height = bmp.Height - (2 * BORDER_WIDTH); 

     using (Graphics g = Graphics.FromImage(bmp)) 
     { 
      g.Clear(Color.Black); 
      Pen pen = new Pen(color); 
      int size = data.Length; 
      for (int iPixel = 0; iPixel < width; iPixel++) 
      { 
       // determine start and end points within WAV 
       int start = (int)((float)iPixel * ((float)size/(float)width)); 
       int end = (int)((float)(iPixel + 1) * ((float)size/(float)width)); 
       float min = float.MaxValue; 
       float max = float.MinValue; 
       for (int i = start; i < end; i++) 
       { 
        float val = data[i]; 
        min = val < min ? val : min; 
        max = val > max ? val : max; 
       } 
       int yMax = BORDER_WIDTH + height - (int)((max + 1) * .5 * height); 
       int yMin = BORDER_WIDTH + height - (int)((min + 1) * .5 * height); 
       g.DrawLine(pen, iPixel + BORDER_WIDTH, yMax, 
        iPixel + BORDER_WIDTH, yMin); 
      } 
     } 
     return bmp; 
    } 

    public float[] FloatArrayFromByteArray(byte[] input) 
    { 
     float[] output = new float[input.Length/4]; 
     System.Buffer.BlockCopy(input, 0, output, 0, input.Length); 
     return output; 
    } 
} 
+0

如果不考慮文件頭,等等? –

+0

啊,可以解釋它! –

回答

1

WAV文件是更復雜的格式,比你的代碼是假設。他們有標題和其他描述音頻的元數據。音頻數據通常以帶符號的16位或8位整數值存儲,儘管其他格式也是可能的。您需要找到一個將WAV文件解碼爲可在應用程序中使用的浮點值的庫或使用實用程序將WAV文件轉換爲原始浮點格式文件。

您的規範化代碼也是不正確的。由於樣本值可能爲負值,因此您需要找到樣本絕對值的最大值。你不應該乘以100,因爲它將它們歸一化到-100,100範圍內。

相關問題