// 麦克风实例
Microphone mMicrophone = Microphone.Default;
MemoryStream mStream = new MemoryStream();
/// <summary>
/// 页面构造
/// </summary>
public ChatPanoramaPage()
{
InitializeComponent();
// 模拟XNA的游戏循环Timer to simulate the XNA Game Studio game loop (Microphone is from XNA Game Studio)
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(50);
dt.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
dt.Start();
// 处理它的BufferReady事件
mMicrophone.BufferReady += new EventHandler<EventArgs>(mMicrophone_BufferReady);
}
/// <summary>
/// 将数据写入到buffer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void mMicrophone_BufferReady(object sender, EventArgs e)
{
byte[] buffer = new byte[1024];
int offset = this.mMicrophone.GetData(buffer, 0, 1024);
while (offset > 0)
{
if (this.mStream.Length + offset > 5242000)
{
this.mMicrophone.Stop();
MessageBox.Show("The recording has been stopped as it is too long.");
return;
}
this.mStream.Write(buffer, 0, offset);
offset = this.mMicrophone.GetData(buffer, 0, 1024);
}
}
/// <summary>
/// 点击按钮进行录音,再次点击则播放
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void VoiceImage_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
// 还没有开始录音
if (!isStart)
{
VoiceImage.Source = new BitmapImage(new Uri("/Images/mic_w48.png", UriKind.Relative));
// 录音开始
if (this.mStream != null)
{
this.mStream.Close();
}
this.mStream = new MemoryStream();
if (this.mMicrophone.State != MicrophoneState.Started)
{
this.mMicrophone.Start();
ToastPrompt toast = new ToastPrompt { Message = "录完音后按停止键播放录音" };
toast.Show();
isStart = true;
}
}
else // 已经开始了录音
{
VoiceImage.Source = new BitmapImage(new Uri("/Images/microphone.png", UriKind.Relative));
// 停止录音
if (mMicrophone.State == MicrophoneState.Started)
{
mMicrophone.Stop();
isStart = false;
}
// 播放录音
playRecord();
}
}
/// <summary>
/// 播放录音
/// </summary>
private void playRecord()
{
if (this.mStream == null || this.mStream.Length == 0)
{
return;
}
this.mStream.Position = 0;
SoundEffect soundEffect = new SoundEffect(this.mStream.ToArray(), this.mMicrophone.SampleRate, AudioChannels.Mono);
soundEffect.Play();
}
Windows Phone的录音与回放实现(个人记录)
最新推荐文章于 2025-05-03 16:08:00 发布