那么在.NET(WinForms)中播放简单生成的莫尔斯电码的最佳方式是什么,不需要任何外部文件,也不需要任何第三方库?我只想使用 CLR,没有不必要的依赖。欢迎使用 C# 或 VB.NET 代码。我会多种语言。;P
(我真的不在乎生成什么音频。简单的单频音就可以了。)
有很多方法可以实现你想要的..
我认为对你来说最简单的方法是演奏一些 MIDI 音符。
请参阅这篇文章:http: //msdn.microsoft.com/en-us/magazine/ee336028.aspx
NAudio 库是开源的,如果您对额外的 DLL 真的不满意,您可以将相关的类复制粘贴到您的项目中。
我在其他网站上找到了一半的在线帮助,大约一半我想出了如何做自己。这是我需要的一个几乎理想的解决方案:1:创建一个 MemoryStream,2:将 WAV 文件的字节写入 MemoryStream(它永远不会保存到磁盘,但会像来自 WAV 文件一样播放), 3:寻找 MemoryStream 的开头, 4:播放 MemoryStream 与System.Media.SoundPlayer(memoryStream).Play()
. 而已。其中最困难的部分是创建 WAV 格式的字节流......除非你只是从像我这样的人那里复制代码。:P 这是一个 .NET 方法,可以在没有外部 DLL 或 .NET 外部的任何东西的情况下播放声音:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
{
var mStrm = new MemoryStream();
BinaryWriter writer = new BinaryWriter(mStrm);
const double TAU = 2 * Math.PI;
int formatChunkSize = 16;
int headerSize = 8;
short formatType = 1;
short tracks = 1;
int samplesPerSecond = 44100;
short bitsPerSample = 16;
short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
int bytesPerSecond = samplesPerSecond * frameSize;
int waveSize = 4;
int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
int dataChunkSize = samples * frameSize;
int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
// var encoding = new System.Text.UTF8Encoding();
writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
writer.Write(fileSize);
writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
writer.Write(formatChunkSize);
writer.Write(formatType);
writer.Write(tracks);
writer.Write(samplesPerSecond);
writer.Write(bytesPerSecond);
writer.Write(frameSize);
writer.Write(bitsPerSample);
writer.Write(0x61746164); // = encoding.GetBytes("data")
writer.Write(dataChunkSize);
{
double theta = frequency * TAU / (double)samplesPerSecond;
// 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
// we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
double amp = volume >> 2; // so we simply set amp = volume / 2
for (int step = 0; step < samples; step++)
{
short s = (short)(amp * Math.Sin(theta * (double)step));
writer.Write(s);
}
}
mStrm.Seek(0, SeekOrigin.Begin);
new System.Media.SoundPlayer(mStrm).Play();
writer.Close();
mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
快乐编码!
-Humilulo<><
private static void Main(string[] args)
{
int freq = 500;
int duration = 500;
Console.Beep(freq, duration); //S
Console.Beep(freq, duration);
Console.Beep(freq, duration);
Console.Beep(freq, duration * 2); //O
Console.Beep(freq, duration * 2);
Console.Beep(freq, duration * 2);
Console.Beep(freq, duration); //S
Console.Beep(freq, duration);
Console.Beep(freq, duration);
}