1 月 4 2010
[C#] 取得 wav 檔案格式
前陣子,在工作上剛好需要對 wav 檔案格式進行判定,可是 NAudio 製作出來的格式用來作判斷又有錯誤,所以土法煉鋼寫了一個小 class:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
class WavInfo
{
private String _Error;
public String Error
{
get
{
return this._Error;
}
}
private Boolean _PCM;
public Boolean PCM
{
get
{
return this._PCM;
}
}
private uint _Channel;
public uint Channel
{
get
{
return this._Channel;
}
}
private uint _SampleRate;
public uint SampleRate
{
get
{
return this._SampleRate;
}
}
private uint _BitsPerSample;
public uint BitsPerSample
{
get
{
return this._BitsPerSample;
}
}
private uint _ByteRate;
public uint ByteRate
{
get
{
return this._ByteRate;
}
}
private uint _BlockAlign;
public uint BlockAlign
{
get
{
return this._BlockAlign;
}
}
public WavInfo(String FileName)
{
try
{
FileStream FS = File.OpenRead(@FileName);
Byte[] ReadTmp = new Byte[36];
FS.Read(ReadTmp, 0, 36);
FS.Close();
if (BitConverter.ToUInt16(ReadTmp, 20) == 1)
{
this._PCM = true;
}
this._Channel = BitConverter.ToUInt16(ReadTmp, 22);
this._SampleRate = BitConverter.ToUInt32(ReadTmp, 24);
this._BitsPerSample = BitConverter.ToUInt16(ReadTmp, 34);
this._ByteRate = this._Channel * this._SampleRate * this._BitsPerSample / 8;
this._BlockAlign = this._Channel * this._BitsPerSample / 8;
this._Error = String.Empty;
}
catch (Exception e)
{
this._Error = e.ToString();
}
}
}
- 檢查 Error 是否為空字串,就知道是否成功取得 wav 檔案資訊。
- 檢查 PCM 是否為 true,就知道該檔案是不是 PCM 格式的 wav 檔。
- wav 檔播放的時間會等於 ByteRate。







1 月 7 2010
[Javascript] 從 array 裡隨機挑出不重複的值
Javascript 提供了 For … In … ,我用的還蠻高興的(雖然我很少撰寫 Javascript)。
今天遇到某種特殊需求,我才發現這個迴圈語法並非萬能。
從 array 裡隨機挑出不重複的值有兩種情況,一種很單純,For … In … 迴圈可以處理的很好:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x; while(fruits.length > 0) { var r = Math.floor( Math.random() * fruits.length ); var n = fruits[r]; document.write("Choosen[" + r + "]: " + n + "<br />"); document.write("Array: " + fruits + "<br />"); for(x in fruits) { if (fruits[x] == n) { fruits.splice(x, 1); } } }若是 array 裡面已經存在重複的值,而且 array 的資料的來源不方便控制(例如是 HTML 裡面的 li 物件),For … In … 這種方便的迴圈語法就必須放棄,改用傳統的 for 迴圈:
var fruits = [ "Banana", "Banana", "Orange", "Orange", "Banana", "Apple", "Apple", "Orange", "Mango" ]; var i=0; while(fruits.length > 0) { var r = Math.floor( Math.random() * fruits.length ); var n = fruits[r]; document.write("Choosen[" + r + "]: " + n + "<br />"); document.write("Array: " + fruits + "<br />"); for(i=0; i<fruits.length; i++) { if (fruits[i] == n) { fruits.splice(i, 1); i--; } } }By Joe Horn • Javascript, WWW 4 • Tags: array, For loop, Javascript, random