有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中播放除嘟嘟声以外的声音?

因此,目前,这是Java中的“嘟嘟声”(在某些操作系统上不是真正的嘟嘟声):

Toolkit.getDefaultToolkit().beep();

但是代码使用我电脑的“哔”声/警报声

有办法取代它吗


共 (2) 个答案

  1. # 1 楼答案

    只需创建这样一个函数,并在任何地方调用它,例如单击按钮或侦听器

    public void alert() {
    
        try{
    
            InputStream inputStream = getClass().getResourceAsStream("/sounds/sms.wav"); //Note this is path to whatever wav file you want
                AudioStream audioStream = new AudioStream(inputStream);
                AudioPlayer.player.start(audioStream);
            }
        catch (IOException e) {
           // Whatever exception you please;
        }
           // return inputStream;
    
    }
    

    另请注意:Audiostream类是Java专有的,如果它是一个很长的声音字节,需要随时停止,您可以调用AudioPlayer。游戏者通过定时器、线程中断或按钮点击,在任何地方停止(音频流)

  2. # 2 楼答案

    我发现了一个interesting code here,它使用的声音不同于嘟嘟声:

    import javax.sound.sampled.*;
    
    public class SoundUtils {
    
      public static float SAMPLE_RATE = 8000f;
    
      public static void tone(int hz, int msecs) 
         throws LineUnavailableException 
      {
         tone(hz, msecs, 1.0);
      }
    
      public static void tone(int hz, int msecs, double vol)
          throws LineUnavailableException 
      {
        byte[] buf = new byte[1];
        AudioFormat af = 
            new AudioFormat(
                SAMPLE_RATE, // sampleRate
                8,           // sampleSizeInBits
                1,           // channels
                true,        // signed
                false);      // bigEndian
        SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
        sdl.open(af);
        sdl.start();
        for (int i=0; i < msecs*8; i++) {
          double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
          buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
          sdl.write(buf,0,1);
        }
        sdl.drain();
        sdl.stop();
        sdl.close();
      }
    
      public static void main(String[] args) throws Exception {
        SoundUtils.tone(1000,100);
        Thread.sleep(1000);
        SoundUtils.tone(100,1000);
        Thread.sleep(1000);
        SoundUtils.tone(5000,100);
        Thread.sleep(1000);
        SoundUtils.tone(400,500);
        Thread.sleep(1000);
        SoundUtils.tone(400,500, 0.2);
    
      }
    }