当麦克风的振幅超过某个值时,我的目标是暂停当前正在播放的歌曲
但是当振幅增加时,应用程序会突然退出
那是为什么?
如何解决这个问题?
[我做的是我在音乐中播放了一首歌,
打开此应用程序并按下按钮并发出超过该值的声音
然后app突然退出]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using U.Resources;
using Microsoft.Xna.Framework.Audio;
using System.Windows.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
namespace U
{
public partial class MainPage : PhoneApplicationPage
{
//global variables
Microphone microphone = Microphone.Default;
byte[] buffer;
// Constructor
public MainPage()
{
InitializeComponent();
// Timer to simulate the XNA Game Studio game loop (Microphone is from XNA Game Studio)
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(33);
dt.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
dt.Start();
microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
}
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
microphone.BufferDuration = TimeSpan.FromMilliseconds(100);
buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];
microphone.Start();
}
void microphone_BufferReady(object sender, EventArgs e)
{
microphone.GetData(buffer);
for (int i = 0; i < buffer.Length; i += 2)
{
//The value of sample is the amplitude of the signal
short sample = BitConverter.ToInt16(new byte[2] { buffer[i], buffer[i + 1] }, 0);
//getting the absolut value
if (sample < 0) sample *= (-1);
//showing the output
if(sample>1000) pause_music();
}
}
void pause_music()
{
if (MediaPlayer.State == MediaState.Playing)
{
FrameworkDispatcher.Update();
MediaPlayer.Pause();
}
}
}
}
答案 0 :(得分:3)
它正在崩溃,因为它正在进行StackOverflow!
您不应该在FrameworkDispatcher.Update()
方法内拨打pause_music()
!
这只会导致另一次调用microphone_BufferReady
然后调用pause_music
等等,并且会提供堆栈溢出。
只需删除该行,并记得致电microphone.Stop()
,它就能正常工作:)