简体   繁体   中英

How To Play A Beep/Alert Sound On Mac In Java

I have tried using both

Toolkit.getDefaultToolkit().beep(); and

System.out.println("\\007");

and neither are actually playing a sound. I tried running the code in my IDE (CodeRunner 2) and in Terminal to see if it made a difference, which it didn't.

If anyone know another way to do this or why it isn't working, please let me know

Thanks!

I think you are looking for Runtime#exec(String) :

Runtime.getRuntime().exec(cmd);

This should allow you to get an instance of the current environment in which you can issue such commands.

Or you might try to use it with JNA-Library:

   import com.sun.jna.platform.win32.Kernel32;
   import com.sun.jna.Native;
   import com.sun.jna.Library;

   interface JnaTests extends Library {
    public boolean Beep(int FREQUENCY , int DURATION );
    static Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); 
   static void startBeep() throws InterruptedException { 
   kernel32.Beep(1200, (5000)); 
   Thread.sleep(50); 
  }

}


  package com.sun.jna.platform;


  import com.sun.jna.Library;

   public class win32 {

   private static class MSG implements User32 {

    public MSG() {
    }
   }

  public interface Kernel32 extends Library { // ... (lines deleted for   clarity) ...  
    boolean Beep(int frequency, int duration); 
     //int GetLogicalDrives(); // ... (lines deleted for clarity)   ...      }   
    }
   public interface User32 extends Library { // ... (lines deleted for  clarity) ...  
        // ... (lines deleted for clarity) ... }
   }
  }

  Perhaps you could use the midi class too:



Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ,4);
Track track = sequence.createTrack();
ShortMessage a = new ShortMessage();
a.setMessage(144,9,56,100);
MidiEvent event = new MidiEvent(a, 1);
track.add(event);
sequencer.setSequence(sequence);
sequencer.start();
Thread.sleep(500);
sequencer.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM