如何通过数组定义声音并使用Jbutton播放?

时间:2017-06-12 12:55:17

标签: java audio

我目前正在开发一款非常基本的Magic8Ball游戏,虽然我确实把它改成了精灵主题,现在我决定为游戏添加声音。

基本上我已经准备好了答案的阅读并将它们保存为音频文件(mp3),我想将每个声音归因于相应的数组字符串。

因此,如果语音朗读“我看到它,是的”它应该链接到包含该答案的数组[0]。所以最终,我希望游戏在显示答案时说出播放器的答案。

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];           
    } 
}

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:0)

播放声音的简单示例:

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

class SoundTest {

  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);
  }
}