Skip to content

WindowsMicrophoneStream.cs - Boolean variables never set to True #11848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
DarcyWilson-MU opened this issue May 20, 2025 · 0 comments
Open
Labels

Comments

@DarcyWilson-MU
Copy link

DarcyWilson-MU commented May 20, 2025

Describe the bug

When calling Initialize(), Pause(), Resume(), StartStream() or StartRecording(), none of the Booleans in charge of keeping track of these functions are set tthe state they should be in, and will stay as there were at startup, meaning the if statements within the functions will be skipped in most instances. For instance, StopRecording() will not stop the recording as it is always set the false, even when a recording is started, it will just return an empty string:

public WindowsMicrophoneStreamErrorCode StartRecording(string fileName, bool preview)
{
    if (recording)
    {
        // The microphone stream is already recording, no need to alarm the calling code.
        return WindowsMicrophoneStreamErrorCode.Success;
    }

    return (WindowsMicrophoneStreamErrorCode)MicStartRecording(fileName, preview);
}

...

public string StopRecording()
{
    if (!recording)
    {
        // todo: log message
        return string.Empty;
    }

    StringBuilder fullPath = new StringBuilder();
    MicStopRecording(fullPath);
    recording = false;

    return fullPath.ToString();
}

This is the only instance where a Boolean is set to false as all other calls to stop/resume the stream or uninitialize it do not set anything to false. And no function apart from Dispose() sets their respective Boolean to True.

To reproduce

N/A

Expected behavior

There should be lines which set the state of these Booleans when starting/stopping streams and/or recordings.

Screenshots

N/A

Your setup (please complete the following information)

  • Unity 6 (6000.0.36f1)
  • MRTK Commit [e.g. v2.0] [5c6ab1f]
  • Mixed Reality Toolkit Examples [2.8.3]
  • Mixed Reality Toolkit Microphone Stream Selector [1.0.0]

Target platform (please complete the following information)

  • HoloLens 2

Additional context

I've modified a version of the MicrophoneAmplitudeDemo.cs script to try to set up a system in which I capture an initial 30 seconds of room audio, uninitialise the stream, dispose of it, and then create/initialise it again to record voice audio. The code is extremely early and rough, and I'm not 100% sure if it's possible so if not disregard this, but this is what I've done:

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.MixedReality.Toolkit.Audio;

using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Examples
{
    /// <summary>
    /// Demonstration class using WindowsMicrophoneStream (from com.microsoft.mixedreality.toolkit.micstream) to select
    /// the voice microphone and adjust the spatial awareness mesh based on the amplitude of the user's voice.
    /// </summary>
    [RequireComponent(typeof(AudioSource))]
    public class MicrophoneAmplitudeDemo : MonoBehaviour
    {
#if MICSTREAM_PRESENT
        /// <summary>
        /// Class providing microphone stream management support on Microsoft Windows based devices.
        /// </summary>
        private static WindowsMicrophoneStream m_micStream = null;

        private void Awake()
        {
            // We do not wish to play the ambient room sound from the audio source.
            gameObject.GetComponent<AudioSource>().volume = 0.0f;

            m_micStream ??= new WindowsMicrophoneStream();

            // Setup microphone streams and start timer on Room audio recording

            StartCoroutine(StreamSetup("Room", WindowsMicrophoneStreamType.RoomCapture, 0));

            StartCoroutine(RecordingTimer(30, true));

            StartCoroutine(StreamSetup("Voice", WindowsMicrophoneStreamType.HighQualityVoice, 35));
        }

        private void OnDestroy()
        {
            StopStream();

            m_micStream.Dispose();

            m_micStream = null;
        }

        private void OnDisable()
        {
            StreamState(false);
        }

        private void OnEnable()
        {
            StreamState(true);
        }

        private System.Collections.IEnumerator StreamSetup(string inputStreamName = "DEFAULT_NAME",
            WindowsMicrophoneStreamType inputStreamType = WindowsMicrophoneStreamType.LowQualityVoice,
            uint setupDelay = 0)
        {
            if (setupDelay > 0)
            {
                Debug.Log($"Delaying the setup of the stream for {setupDelay} seconds.");

                yield return new WaitForSeconds((float)setupDelay);
            }

            // Initialise the microphone stream.
            WindowsMicrophoneStreamErrorCode result = m_micStream.Initialize(inputStreamType);
            StreamResult(result, $"Initialising Stream for {inputStreamName} - StreamSetup()");

            // Start the microphone stream.
            // Do not keep the data and do not preview.
            result = m_micStream.StartStream(false, false);
            StreamResult(result, $"Starting Stream for {inputStreamName} - StreamSetup()");

            result = m_micStream.StartRecording($"{inputStreamName}Rec_{Time.frameCount}.wav", false);
            StreamResult(result, $"Starting Recording for {inputStreamName} - StreamSetup()");
        }

        private System.Collections.IEnumerator RecordingTimer(uint inputRecordingTime = 5,
            bool stopStream = false)
        {
            Debug.Log($"Recording will be stopped after {inputRecordingTime} seconds.");

            yield return new WaitForSeconds((float)inputRecordingTime);

            m_micStream.StopRecording();

            Debug.Log($"Recording has been stopped after {inputRecordingTime} seconds.");

            if(stopStream == true)
            {
                Debug.Log("Stopping the stream post-recording.");

                StopStream();

                Debug.Log("The stream has been stopped post-recording.");
            }
        }

        private void StopStream()
        {
            if (m_micStream != null)
            {
                m_micStream.StopRecording();

                m_micStream.StopStream();

                m_micStream.Uninitialize();
            }
            else
            {
                Debug.LogError("`m_micStream` is null! Nothing to stop.");
            }
        }

        private void StreamState(bool resumeStream = false)
        {
            if (m_micStream != null)
            {
                WindowsMicrophoneStreamErrorCode result;

                if (resumeStream == false)
                {
                    result = m_micStream.Pause();
                }
                else
                {
                    result = m_micStream.Resume();
                }

                StreamResult(result, "Switching Stream State");
            }
            else
            {
                Debug.LogError("`m_micStream` is null! Cannot change state.");
            }
        }

        private void StreamResult(WindowsMicrophoneStreamErrorCode inputStreamErrorCode = WindowsMicrophoneStreamErrorCode.Success,
            string extraNotes = "")
        {
            if (inputStreamErrorCode != WindowsMicrophoneStreamErrorCode.Success)
            {
                Debug.LogError($"Microphone stream error. {extraNotes}: {inputStreamErrorCode}");
            }
            else
            {
                Debug.Log($"Microphone stream success. {extraNotes}: {inputStreamErrorCode}");
            }
        }
#endif // MICSTREAM_PRESENT
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant