如何寫一段程式來讓Sound Card發出1KHz聲音? |
尚未結案
|
asvmfd
一般會員 發表:46 回覆:30 積分:15 註冊:2004-11-09 發送簡訊給我 |
|
johnpage
初階會員 發表:0 回覆:79 積分:40 註冊:2004-08-07 發送簡訊給我 |
|
Stallion
版主 發表:52 回覆:1600 積分:1995 註冊:2004-09-15 發送簡訊給我 |
以下程序忘記是從Torry's page還是哪裡收集來的?
小弟試用過,可以產生指定頻率並可指定聲音大小,雖然是Delphi版的,應該很容易改成BCB。 <textarea cols="60" rows="10" class="delphi" name="code"> uses MMSystem; type TVolumeLevel = 0..127; procedure MakeSound(Frequency{Hz}, Duration{mSec}: Integer; Volume: TVolumeLevel); {writes tone to memory and plays it} var WaveFormatEx: TWaveFormatEx; MS: TMemoryStream; i, TempInt, DataCount, RiffCount: integer; SoundValue: byte; w: double; // omega ( 2 * pi * frequency) const Mono: Word = $0001; SampleRate: Integer = 11025; // 8000, 11025, 22050, or 44100 RiffId: string = 'RIFF'; WaveId: string = 'WAVE'; FmtId: string = 'fmt '; DataId: string = 'data'; begin if Frequency > (0.6 * SampleRate) then begin ShowMessage(Format('Sample rate of %d is too Low to play a tone of %dHz', [SampleRate, Frequency])); Exit; end; with WaveFormatEx do begin wFormatTag := WAVE_FORMAT_PCM; nChannels := Mono; nSamplesPerSec := SampleRate; wBitsPerSample := $0008; nBlockAlign := (nChannels * wBitsPerSample) div 8; nAvgBytesPerSec := nSamplesPerSec * nBlockAlign; cbSize := 0; end; MS := TMemoryStream.Create; with MS do begin {Calculate length of sound data and of file data} DataCount := (Duration * SampleRate) div 1000; // sound data RiffCount := Length(WaveId) Length(FmtId) SizeOf(DWORD) SizeOf(TWaveFormatEx) Length(DataId) SizeOf(DWORD) DataCount; // file data {write out the wave header} Write(RiffId[1], 4); // 'RIFF' Write(RiffCount, SizeOf(DWORD)); // file data size Write(WaveId[1], Length(WaveId)); // 'WAVE' Write(FmtId[1], Length(FmtId)); // 'fmt ' TempInt := SizeOf(TWaveFormatEx); Write(TempInt, SizeOf(DWORD)); // TWaveFormat data size Write(WaveFormatEx, SizeOf(TWaveFormatEx)); // WaveFormatEx record Write(DataId[1], Length(DataId)); // 'data' Write(DataCount, SizeOf(DWORD)); // sound data size {calculate and write out the tone signal} // now the data values w := 2 * Pi * Frequency; // omega for i := 0 to DataCount - 1 do begin SoundValue := 127 trunc(Volume * sin(i * w / SampleRate)); // wt = w * i / SampleRate Write(SoundValue, SizeOf(Byte)); end; {now play the sound} sndPlaySound(MS.Memory, SND_MEMORY or SND_SYNC); MS.Free; end; end; </textarea> |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |