java - 如何通过数组对声音进行属性并使用Jbutton播放?

标签 java audio

我目前正在开发一款 Magic8Ball 游戏,非常基础,尽管我确实将其更改为 Sprite 主题,现在我决定为游戏添加声音。

基本上,我已经准备好答案的阅读并将其保存为音频文件(mp3),并且我想将每个语音归因于适当的数组字符串。

因此,如果语音朗读显示“据我所知,是的”,它应该链接到包含该答案的 array[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];           
    } 
}

请帮忙。

谢谢。

最佳答案

播放声音的简单示例:

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

关于java - 如何通过数组对声音进行属性并使用Jbutton播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44500043/

相关文章:

java - 从 .mp3 或 .wav 文件计算频率?

java - 使用流过滤java中的内部和外部列表

java - 生成唯一的注册号

java - 节点 "dynamic"是变量吗?

c# - 尝试播放流中的声音;文件以.mp3开头,然后是byte []数组,然后是流。.为什么它不起作用?

iphone - 将生成的音频发送到UILocalNotification

java - 从服务更改按钮背景

java - 如果我在每个 ZooKeeper 集群中使用多个 Curator 框架实例,我会得到什么结果?

javascript - 如何将当前播放的歌曲保存在 cookie 中?

iphone - 将音频/视频流传输到HTTP服务器以外的iPhone