【问题标题】:Console.Beep how to remove delay in loop?Console.Beep 如何消除循环延迟?
【发布时间】:2016-12-08 17:40:27
【问题描述】:

我正在尝试制作一个程序,您可以在其中输入一个数字,然后它会生成一个数字轨迹。它将它分成数字并根据数字播放不同的哔声。但哔声之间存在延迟。这是项目的代码:

using System;
using System.Collections.Generic;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] numbersWithBeeps = new int [] { 262, 294, 330, 349, 392, 440, 494, 523, 600, 687, 878};
            int input;
            Console.WriteLine("Please enter the number you would like to play.");
            input = Convert.ToInt32(Console.ReadLine());
            input*=10;
            List<int> actualNumbers = new List<int>();
            do{
                if(input%10 == 0) 
                {
                    actualNumbers.Add(0);
                }
                else
                {
                    actualNumbers.Add(input%10);
                }
                input=input/10;
            } while(input > 0);

            for(int i = actualNumbers.Count - 1; i > 0; i--){
                Console.Beep(numbersWithBeeps[actualNumbers[i]], 500);
            }
        }
    }
}

【问题讨论】:

  • 延迟多长时间(以毫秒为单位)?
  • 您是否尝试过将第二个参数的哔哔声的持续时间更改为Console.Beep?当我尝试它时,似乎每次哔哔声后都会有噪音,而不是真正的延迟,但在不同的硬件上运行时可能会有所不同。
  • 请注意,根据this guy:“从单独的线程调用 Console.Beep() 会中断当前正在进行的任何操作。”,因此假设延迟只是 if 上的字面延迟新的Beep 调用中的语句迭代和延迟使其进入硬件,那么一个可能的答案是在一个线程中创建878 哔声,然后在它仍在播放时创建687 哔声在不同的线程中,它可以在 878->687 之间无延迟地播放它。
  • @DanWilson 好像是半秒左右 Juharr 是的,我试过了,但我认为不同的时间会有不同的延迟。我知道没有任何逻辑,但这是我现在可以向自己解释的唯一方法。 Quantic 我会试试这个并告诉你发生了什么

标签: c# .net-core


【解决方案1】:

延迟是由于for 循环迭代造成的。它不会在不包含您的numbersWithBepps[] 之一的迭代中发出哔声。似乎您的整个do{}while 循环也是不必要的。你所做的很多事情对我来说没有意义。您希望用户选择播放的音调吗?那为什么不呢

int iSoundId;
getsound: Console.WriteLine("Enter the number of sound you want to hear:\t");
iSoundId = Convert.ToInt32(Console.ReadLine();
if (iSoundId < 32,767)
    Console.Beep(iSoundId, 500);
else 
{
    Console.WriteLine("Number too high...  Try again:\n);
    goto getSound;
}

另外,就像 juharr 所说,你的持续时间可能是影响它的因素。尝试将持续时间从 500 毫秒降低到 250

【讨论】:

  • 我不希望用户选择它,程序的重点是用户输入一个数字并生成一个轨道,所以用户不知道他在做什么听到。稍后我计划添加不同的“种子”之类的东西。根据“种子”,曲目每次听起来都会完全不同。
  • 我确信用户不知道它会发出什么音调,因为整数值是基于应用于扬声器的赫兹级别。无论哪种方式,就像我说的那样,您可以尝试将 duration 时间降低到 250 或更低。它应该解决问题。试试看,让我知道它是否有效......否则,我会尝试为您找出更详细的内容。
  • 延迟确实存在,与它周围的循环完全无关。 Console.Beep 在提示音后有延迟,很烦人。
猜你喜欢
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2017-05-02
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多