音频可以在静态嵌套类中实现吗?



所以我一直在尝试将这个音频实现到我的主类中。我的主类包含其他方法,我不会包含这些方法,以防止我的帖子太长。我认为代码出错是因为out.audio audio = new out.audio ();因为我要么把它放在错误的方法中,要么我没有使用正确的变量。我仍然是一个非常初学者的编码人员,所以我已经对我的代码中发生的事情感到困惑。我所知道的是,仅单独运行音频类(而不是嵌套)是有效的。

我是否正确格式化了嵌套类,是否可以嵌套音频?

import java.awt.*;
import hsa.Console;
import java.awt.image.*;
import java.util.Random;
import sun.audio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class out implements ImageObserver
{
//lots of code and other methods here so I'm going to leave it out
public static class audio extends Thread
{
out.audio audio = new out.audio ();
public void run ()
{
while (true)
{
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try
{
InputStream test = new FileInputStream ("Music long.au");
BGM = new AudioStream (test);
AudioPlayer.player.start (BGM);
//MD = BGM.getData();
//loop = new ContinuousAudioDataStream(MD);
}
catch (FileNotFoundException e)
{
System.out.print (e.toString ());
}
catch (IOException error)
{
System.out.print (error.toString ());
}
MGP.start (loop);
try
{
Thread.sleep (200000);
}
catch (InterruptedException ie)
{
}
try
{
Thread.sleep (1500);
}
catch (InterruptedException ie)
{
}
}
}
public static void main (String[] args)
{
c = new Console ();
audio t1 = new audio ();
t1.start ();
for (;;)
{
c.println ("");
break;
}
} // main method
} // audio class
} //out class

如果你问什么时候使用嵌套类,那么答案是按照你的要求和设计。您可以自由使用嵌套类,但有时如果做得不正确,它会让您难以理解设计和对它的更改。

我引用的是甲骨文官方文件

使用嵌套类的令人信服的理由包括:

  1. 这是一种对仅在一个地方使用的类进行逻辑分组的方法
  2. 它增加了封装
  3. 它可以带来更具可读性和可维护性的代码

==更新==

正如我所提到的,对我来说,将audio作为内部类是没有意义的,但同样取决于您的设计/要求,我也不确定您为什么在内部类中声明您的主要方法?所以,我建议你

class out
{
public static void main (String[] args)
{
//lots of code
}
}
class ImageImp implements ImageObserver
{
//lots of code and other methods here so I'm going to leave it out
}

然后你应该拿出内部类

class audio extends Thread
{
public void run ()
{
//code here
}
}

你的设计应该很简单,应该有意义。不要试图将所有内容都放在一个类中,直到真正需要它。

最新更新