如何将音频从麦克风传输到扬声器?

时间:2013-01-18 19:01:17

标签: windows-phone-7 audio windows-phone-8 windows-phone microphone

我希望将音频直接从麦克风传输到默认音频输出媒体,无论是扬声器还是3.5毫米插孔。

我发现用于播放音频的机制似乎取决于在SoundEffect中提供静态的字节数,如下所示:

SoundEffect sound = new SoundEffect(stream.ToArray(), microphone.SampleRate, AudioChannels.Mono);
soundInstance = sound.CreateInstance();
soundIsPlaying = true;
soundInstance.Play();

我可以不断播放500毫秒或更短时间的SoundEffects来实现我的目标,但我想知道是否有更复杂的方法让麦克风不断写入MemoryStream,音频播放控件可以连续读取。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我通过使用使用麦克风为MediaElement Player提供样本的类扩展MediaStreamSource类来解决此问题。

如果对这段代码有任何需求,我会很乐意将它发布到某个地方。现在,这里有一段代码片段可以帮助你,如果你想做同样的事情:

// Provides audio samples from AudioSampleProvider property.
//  (MediaStreamType parameter will always equal Audio.)
protected override void GetSampleAsync(MediaStreamType mediaStreamType)
{
    // start the microphone capture if it's not started yet
    if (microphone.State == MicrophoneState.Stopped)
    {
        microphone.Start();
    }
}

// gets called back when the microphone's buffer is ready
private void microphone_BufferReady(object sender, EventArgs e)
{
    // Retrieve audio data
    microphone.GetData(buffer);

    // Reset MemoryStream object
    memoryStream.Seek(0, SeekOrigin.Begin);

    // Write the newly acquired data into the memory stream
    memoryStream.Write(buffer, 0, buffer.Length);

    // Send out the sample
    ReportGetSampleCompleted(new MediaStreamSample(mediaStreamDescription,
                                                    memoryStream,
                                                    0,
                                                    buffer.Length,
                                                    0, 
                                                    mediaSampleAttributes));
}

每当返回麦克风缓冲区时,您基本上只会报告示例已准备就绪。这样可以顺利播放。

答案 1 :(得分:0)

尼科

在尝试MegaPhone项目时,我遇到以下错误“对象引用未设置为对象的实例。”。 你看看吗?感谢

在MS.Internal.XcpImports.CheckHResult(UInt32 hr)    在MS.Internal.XcpImports.MediaStreamSource_OnGetSampleCompleted(MediaElement mediaElement,Int32 streamIndex,StreamInteropWrapper streamWrapper,InternalStreamWrapper internalStream,Int64 offset,Int64 count,Int64 timeInHundredNanoseconds,Int64 durationInHundredNanoseconds,Int32 attributeCount,Int32 [] attributeLengths,StringBuilder attributes)    在System.Windows.Controls.MediaElement.MediaSourceReportGetSampleCompleted(MediaStreamSample mediaStreamSample)    在System.Windows.Media.MediaStreamSource.ReportGetSampleCompleted(MediaStreamSample mediaStreamSample)    在Megaphone.MicrophoneSource.microphone_BufferReady(对象发送者,EventArgs e)    在Microsoft.Xna.Framework.Audio.Microphone.OnBufferReady(EventArgs args)    在Microsoft.Xna.Framework.Audio.MicrophoneCollection.OnBufferReady(UInt32句柄)    在Microsoft.Xna.Framework.FrameworkDispatcher.Update()    在Megaphone.MainPage.dt_Tick(对象发件人,EventArgs e)