这篇文章属于学习笔记,拿给自己看的,只贴了代码,除了注释没有做过多的解释,还请通过“搜索娘”找到这篇罪孽文章的童鞋原谅
Microphone microphone = Microphone.Default;
MemoryStream audioStream = new MemoryStream();
SoundEffectInstance recordedSound;
bool isRecording = false;//是否正在录音
byte[] buffer;
bool recordingStopped = false;
// Constructor
public MainPage()
{
InitializeComponent();
//模拟XNA的loop
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(30);
dt.Tick += new EventHandler(dt_Tick);
dt.Start();
SoundEffect.MasterVolume = 1.0f;
}
void dt_Tick(object sender, EventArgs e)
{
try
{
FrameworkDispatcher.Update();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
if (recordingStopped)
{
recordingStopped = false;
Debug.WriteLine("准备播放声音");
//如果已经停止录音 则播放声音
Thread th = new Thread(new ThreadStart(() => {
//多声道播放语音
SoundEffect sound = new SoundEffect(audioStream.ToArray(), microphone.SampleRate, AudioChannels.Stereo);
Debug.WriteLine("声音流大小:"+audioStream.ToArray().Length.ToString());
recordedSound = sound.CreateInstance();
Dispatcher.BeginInvoke(() => {
recordedSound.Pitch = (float)pitchSlider.Value;
recordedSound.Pan = (float)panSlider.Value;
recordedSound.Volume = (float)volSlider.Value;
});
recordedSound.Play();
}));
th.IsBackground = true;
th.Start();
Debug.WriteLine("开始播放声音");
}
}
private void recordButton_Click(object sender, RoutedEventArgs e)
{
if (!isRecording)
{
//开始录音
if (Microphone.Default == null)
{
return;
}
//缓冲时间为500毫秒
microphone.BufferDuration = TimeSpan.FromMilliseconds(500);
//500毫秒需要的缓冲区的大小
buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
audioStream.SetLength(0);
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
microphone.Start();
isRecording = true;//下次点击的时候 结束录音
recordButton.Content = "完成录音录音";
}
else
{
//停止录音
recordButton.Content = "开始录音";
microphone.Stop();
recordingStopped = true;
isRecording = false;
}
}
void microphone_BufferReady(object sender, EventArgs e)
{
microphone.GetData(buffer);
//写入内存流中
audioStream.Write(buffer, 0, buffer.Length);
}