我在控制台中编写程序,启动时先播放音乐,然后播放动画。帮助同时制作动画和音乐。通过互联网遭到破坏,一无所获
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Media;
using System.Threading;
namespace Animation_and_music
{
class animation
{
public void music()
{
SoundPlayer player = new SoundPlayer("C:\\audio.wav");
player.PlaySync();
}
public void gif()
{
Console.SetWindowSize(102, 49);
Image image = Image.FromFile(@"1.gif");
FrameDimension dimension = new FrameDimension(image.FrameDimensionsList[0]);
int frameCount = image.GetFrameCount(dimension);
StringBuilder sb;
int left = Console.WindowLeft, top = Console.WindowTop;
char[] chars = { '#', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ' };
for (int i = 0; ; i = (i + 1) % frameCount)
{
sb = new StringBuilder();
image.SelectActiveFrame(dimension, i);
for (int h = 0; h < image.Height; h++)
{
for (int w = 0; w < image.Width; w++)
{
Color cl = ((Bitmap)image).GetPixel(w, h);
int gray = (cl.R + cl.R + cl.B) / 3;
int index = (gray * (chars.Length - 1)) / 255;
sb.Append(chars[index]);
}
sb.Append('\n');
}
Console.SetCursorPosition(left, top);
Console.Write(sb.ToString());
System.Threading.Thread.Sleep(50);
}
}
static Image ScaleImage(Image source, int width, int height)
{
Image dest = new Bitmap(width, height);
using (Graphics gr = Graphics.FromImage(dest))
{
gr.FillRectangle(Brushes.White, 0, 0, width, height);
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
float srcwidth = source.Width;
float srcheight = source.Height;
float dstwidth = width;
float dstheight = height;
if (srcwidth <= dstwidth && srcheight <= dstheight)
{
int left = (width - source.Width) / 2;
int top = (height - source.Height) / 2;
gr.DrawImage(source, left, top, source.Width, source.Height);
}
else if (srcwidth / srcheight > dstwidth * dstheight)
{
float cy = srcheight / srcwidth * dstwidth;
float top = ((float)dstheight - cy) / 2.0f;
if (top < 1.0f) top = 0;
gr.DrawImage(source, 0, top, dstwidth, cy);
}
else
{
float cx = srcwidth / srcheight * dstheight;
float left = ((float)dstwidth - cx) / 2.0f;
if (left < 1.0f) left = 0;
gr.DrawImage(source, 0, left, cx, dstheight);
}
return dest;
}
}
}
}
“ static void Main(string [] args)”在另一个代码中
在此先感谢您的帮助 (对不起,我的英语,我使用翻译器)
答案 0 :(得分:3)
您的问题是,您试图在一个线程中同时执行两项操作,这是不可能的,一个线程一次只能执行一项操作。您需要使用多个线程来实现您的目标,在这种情况下,这很简单,只需使用player.Play();
而不是player.PlaySync();
。
player.Play();
自动启动一个新线程并在其中运行任务。
Here是C#中线程的很好的教程/简介
答案 1 :(得分:0)
正如@MindSwipe所说,您需要使用更多线程。
示例:
class Animation
{
public Animation
{
Thread mythread = new Thread(DoSomething);
Thread mythread2 = new Thread(DoSomething2);
mythread.Start();
mythread2.Start();
}
public void DoSomething()
{
Do_gif_animation();
}
public void DoSomething2()
{
Do_music();
}
}