user3218743
user3218743

Reputation: 589

Windows Phone application crashes when pausing the current song

My goal is pausing the currently playing song when the amplitude of the microphone exceeds some value.
But the apps exit suddenly when the amplitude increase that value.
Why is that?
How to fix this?

[What I did was I played a song in music,
opened this app and press the button and acted a sound that exceed the value.
Then the app exit suddenly]

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();
        }
    }




}

}

Upvotes: 1

Views: 220

Answers (1)

Paolo Tagliapietra
Paolo Tagliapietra

Reputation: 186

It is crashing because it's going StackOverflow!

You should not call FrameworkDispatcher.Update() from within pause_music() method! That would just result in another call to microphone_BufferReady and then pause_music etc etc and your stack overflow is served.

Just remove that line and remember to call microphone.Stop() and it will work :)

Upvotes: 3

Related Questions