Windows Phone 錄製音頻

來源:互聯網
上載者:User

  Windows Phone 提供的訪問麥克風的類為 Microsoft.Xna.Framework.Audio.Microphone ,該類屬於 XNA Framework , 若要在 Silverlight 中訪問 Windows Phone 麥克風,同樣需要使用此類。所以需要添加引用 Microsoft.Xna.Framework。
  1.聲明局部變數,擷取麥克風單例。

        //麥克單例
private Microphone microphone = Microphone.Default;
//每次捕獲音頻緩衝
private byte[] buf;
//音頻流儲存區
private MemoryStream audioStream;

  2.由於在XNA中每33fp就會更新畫面一次,但在Silverlight Application並沒有這樣的機制,為了確保錄音的功能持續的更新狀態與進行擷取動作,因此,需要透過指定一個定期執行 FrameworkDispatcher.Update() 的事件。

        //設定定時器
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(33);
timer.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
timer.Start();

  3.設定錄音相關資訊,啟動錄音。

        //設定1秒的緩衝區,沒擷取1秒音頻就會調用一次BufferReady事件
microphone.BufferDuration = TimeSpan.FromMilliseconds(1000);
//分配1秒音頻所需要的緩衝區
buf = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
audioStream = new MemoryStream();
//BufferReady事件
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
//啟動錄音
microphone.Start();

  3.實現 BufferReady 事件處理常式。該處理常式將麥克風的資料複製到緩衝區中並將該緩衝區寫入一個流。

        void microphone_BufferReady(object sender, EventArgs e)
{
//將麥克風的資料複製到緩衝區中
microphone.GetData(buf);
//將該緩衝區寫入一個流
audioStream.Write(buf, 0, buf.Length);
}

  4.停止錄音

        //停止錄音
microphone.Stop();
microphone.BufferReady -= new EventHandler<EventArgs>(microphone_BufferReady);
audioStream.Flush();
//將資料流轉換為byte,recording中即為音頻資料
byte[] recording = audioStream.ToArray();
audioStream.Dispose();

  5.播放錄音

        //播放錄音
SoundEffect sound = new SoundEffect(audioStream.ToArray(), microphone.SampleRate, AudioChannels.Mono);
sound.Play();

  通過錄製的byte位元組流資料,可以通過SoundEffect類播放,相當容易。但是如果想通過其他方式播放或在要到處音頻資料,則需要將音頻資料以檔案的方式儲存到隔離儲存區 (Isolated Storage)中。關於錄製音訊儲存將在後續介紹。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.