2017-06-12 51 views
0

即時工作在Magic8Ball遊戲中,非常基本,雖然我確實將它改爲精靈主題,現在我已決定向遊戲添加聲音。基本上我已經準備好了答案的閱讀並將它們保存爲一個音頻文件(mp3),並且我想將每個聲音歸入相應的數組字符串。所以如果語音閱讀說「我看到它,是的」它應該被鏈接到包含該答案的數組[0]。因此,最終,我希望遊戲在顯示答案時向玩家說出答案。如何通過數組聲明聲音並使用Jbutton播放它

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.File; 
import java.io.IOException; 
import java.util.Random; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.imageio.ImageIO; 



public class CompSays02GUI extends JFrame { 

public static void main(String[] args) { 
    //set look and feel for UI as deault operating system look 
    try { 
     for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    //start the program 
    new CompSays02GUI().setVisible(true); 
} 

public CompSays02GUI() { 
    setTitle("Genie Game"); 
    setSize(725, 525); 
    setLocationRelativeTo(null); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setLayout(new BorderLayout()); 
    addComponents(); 
} 

private void addComponents() { 
    MainPanel background = new MainPanel(); 
    add(background, BorderLayout.CENTER); 
} 

private class MainPanel extends JPanel implements ActionListener { 

    private JTextField question; 
    private JButton ask; 
    private JButton exit; 
    private JLabel result; 

    /** 
    * Initialize MainPanel 
    */ 
    public MainPanel() { 
     setLayout(null); // set to free layout 
     addComponents(); 
    } 

    /** 
    * Add components to JPanel 
    */ 
    private void addComponents() { 
     //question text field 
     question = new JTextField(); 
     question.setForeground(Color.BLUE); //set the foreground color 
     question.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16)); // set the font 
     question.setBounds(100, 120, 250, 33); // set location, width and height 
     add(question); 
     //ask button 
     ask = new JButton("Ask"); 
     ask.addActionListener(this); // add action listener to handle button click 
     ask.setBackground(Color.BLUE); // set background color 
     ask.setForeground(Color.WHITE); // set text color 
     ask.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); // set font 
     ask.setBounds(400, 120, 80, 33); // set location, width and height 
     add(ask); 
     //exit button 
     exit = new JButton("Exit"); 
     exit.addActionListener(this); 
     exit.setBackground(Color.RED); 
     exit.setForeground(Color.WHITE); 
     exit.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); 
     exit.setBounds(500, 120, 80, 33); 
     add(exit); 
     //result label 
     result = new JLabel(); 
     result.setForeground(Color.BLACK); 
     result.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 22)); 
     result.setBounds(250, 200, 400, 33); 
     add(result); 

    } 

    /** 
    * Paint the image in background 
    * 
    * @param g Graphics 
    */ 
    @Override 
    public void paintComponent(Graphics g) { 
     try { 
      super.paintComponents(g); 
      //read the image 
      Image img = ImageIO.read(new File("resources/genie.png")); 
      //draw in background of panel 
      g.drawImage(img, 0, 0, null); 
     } catch (IOException ex) { // else if image not found, print error 
      System.out.println("Error: Image 'genie.png' not found"); 
      System.out.println(ex.getMessage()); 
     } 
    } 

    /** 
    * Handle the ask and exit buttons clicks 
    * 
    * @param e ActionEvent 
    */ 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     // if ask button clicked 
     if (e.getSource() == ask) { 
      //get question 
      String ques = question.getText(); 
      //if it's empty 
      if (ques.isEmpty()) { 
       JOptionPane.showMessageDialog(this, "Error: Your question " 
         + "was not stated as a yes or no. Try again.", 
         "Error", JOptionPane.ERROR_MESSAGE); 
      } 
      //check the question and continue else if it's valid 
      if (questionCheck(ques)) { 
       result.setText(printResult(ques)); 

      } 
     } 
     // if exit button clicked 
     if (e.getSource() == exit) { 
      //print message 
      JOptionPane.showMessageDialog(this, "Thanks for playing!\n\n"); 

     } 
    } 

    /** 
    * Check else if the question is valid 
    * 
    * @param ques String 
    * @return boolean 
    */ 
    private boolean questionCheck(String ques) { 
     // They have a valid question 
     boolean result = true; 
     //else if it's not yes/no question 
     if (ques.indexOf("who") != -1 || ques.indexOf("what") != -1 
       || ques.indexOf("why") != -1 || ques.indexOf("which") != -1 
       || ques.indexOf("how") != -1 || ques.indexOf("When") != -1 
       || ques.indexOf("whats") != -1 || ques.indexOf("what's") != -1) { 
      result = false; 
      JOptionPane.showMessageDialog(this, "Error: Your question was " 
        + "not stated as a yes or no. Try again.", "Error", 
        JOptionPane.ERROR_MESSAGE); 
     } 
     return result; 
    } 

    /** 
    * Generate random number from 1-20 and return the result answer 
    * 
    * @return String 
    */ 
    private String printResult(String ques) { 
     String[] answers = new String [20]; 
     answers[0] = "As i see it, yes"; 
     answers[1] = "It is certain"; 
     answers[2] = "It is decidedly so"; 
     answers[3] = "Most Likely"; 
     answers[4] = "Outlook looking good"; 
     answers[5] = "Sign points to yes"; 
     answers[6] = "Without a doubt"; 
     answers[7] = "Yes"; 
     answers[8] = "Yes, definitely"; 
     answers[9] = "You shouldn't rely on it"; 
     answers[10] = "Reply hazy, try again"; 
     answers[11] = "Try again later"; 
     answers[12] = "Better not tell you now"; 
     answers[13] = "Cannor predict now"; 
     answers[14] = "Concentrate and ask again"; 
     answers[15] = "Don't count on it"; 
     answers[16] = "My reply is... NO!"; 
     answers[17] = "My sources say no"; 
     answers[18] = "Outlook not so good"; 
     answers[19] = "Very doubtful"; 

     Random nexGen = new Random(); 
     int nextAnswer = nexGen.nextInt(answers.length); 
     return answers[nextAnswer]; 


    } 
} 

}

回答

0

用於播放聲音簡單的例子:

import java.awt.event.*; 
import javax.swing.*; 
import javax.sound.sampled.*; 
import java.net.URL; 
import java.io.*; 

class TestSound { 

    public static void main(String[] args) throws Exception { 
    URL urlToSound = new URL("file:c:/java/gun1.wav"); 
// URL urlToSound = new URL("file:c:/java/flyby1.wav"); 
    AudioInputStream ais = AudioSystem.getAudioInputStream(urlToSound); 
    final Clip clip = AudioSystem.getClip(); 
    clip.open(ais); 
    JButton button = new JButton("Play Sound"); 
    button.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent ae) { 
      clip.setFramePosition(0); 
      clip.start(); 
     } 
     }); 
    JOptionPane.showMessageDialog(null, button); 
    } 
}