简体   繁体   English

Java如何在循环中的每次迭代中播放声音?

[英]Java How would I play a sound for every iteration in a loop?

Example: 例:

For(int i=0; i<4; i++)
playSound("Sound.wav");

I have the following classes: 我有以下课程:

Main 主要

import java.io.IOException;
import java.util.*;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class MainClass 
{
    public static void main (String [] args) 
    throws UnsupportedAudioFileException, IOException, LineUnavailableException, InterruptedException
    {

        Thread main = new Thread();
        Thread sound = new Thread();
        main.start();

        Scanner in = new Scanner (System.in);

        Encode MorseCode = new Encode();


        System.out.print("Enter a Phrase: ");
        String input = in.next();

        String selected = "";
        String converted = "";
        String morse = "";


        for (int i = 0; i < input.length(); i++) 
        {
            //for every character instantiate a new sound object
            playSound ps = new playSound();

            //Select the next character
            selected = input.charAt(i) +"";

            // Convert the character
            converted = MorseCode.getEncode(selected);

            //Trying to  pause the main thread until the sound clip finishes
            if(converted == ".")
            {
                //set main thread to sleep for duration of sound clip
                //main.sleep(ps.getWait()*1000);
                main.yield();

                //start other thread to complete the task of playing the soudn
                sound.start();
                ps.playBlip();
            }   
            main.join();
            morse = morse +" "+converted;
            converted = "";
        }

        System.out.print("Morse Code: "+morse);

    }
}

Encoder 编码器

public class Encode
{
    public Encode(){}

    public String getEncode(String toEncode)
    {
        String morse = toEncode;

        if (toEncode.equalsIgnoreCase("a"))
            morse = ".-";
        if (toEncode.equalsIgnoreCase("b"))
            morse = "-...";
        if (toEncode.equalsIgnoreCase("c"))
            morse = "-.-.";
        if (toEncode.equalsIgnoreCase("d"))
            morse = "-..";
        if (toEncode.equalsIgnoreCase("e"))
            morse = ".";
        if (toEncode.equalsIgnoreCase("f"))
            morse = "..-.";
        if (toEncode.equalsIgnoreCase("g"))
            morse = "--.";
        if (toEncode.equalsIgnoreCase("h"))
            morse = "....";
        if (toEncode.equalsIgnoreCase("i"))
            morse = "..";
        if (toEncode.equalsIgnoreCase("j"))
            morse = ".---";
        if (toEncode.equalsIgnoreCase("k"))
            morse = "-.-";
        if (toEncode.equalsIgnoreCase("l"))
            morse = ".-..";
        if (toEncode.equalsIgnoreCase("m"))
            morse = "--";
        if (toEncode.equalsIgnoreCase("n"))
            morse = "-.";
        if (toEncode.equalsIgnoreCase("o"))
            morse = "---";
        if (toEncode.equalsIgnoreCase("p"))
            morse = ".--.";
        if (toEncode.equalsIgnoreCase("q"))
            morse = "--.-";
        if (toEncode.equalsIgnoreCase("r"))
            morse = ".-.";
        if (toEncode.equalsIgnoreCase("s"))
            morse = "...";
        if (toEncode.equalsIgnoreCase("t"))
            morse = "-";
        if (toEncode.equalsIgnoreCase("u"))
            morse = "..-";
        if (toEncode.equalsIgnoreCase("v"))
            morse = "...-";
        if (toEncode.equalsIgnoreCase("w"))
            morse = ".--";
        if (toEncode.equalsIgnoreCase("x"))
            morse = "-..-";
        if (toEncode.equalsIgnoreCase("y"))
            morse = "-.--";
        if (toEncode.equalsIgnoreCase("z"))
            morse = "--..";
        if (toEncode.equalsIgnoreCase("0"))
            morse = "-----";
        if (toEncode.equalsIgnoreCase("1"))
            morse = ".----";
        if (toEncode.equalsIgnoreCase("2"))
            morse = "..---";
        if (toEncode.equalsIgnoreCase("3"))
            morse = "...--";
        if (toEncode.equalsIgnoreCase("4"))
            morse = "....-";
        if (toEncode.equalsIgnoreCase("5"))
            morse = ".....";
        if (toEncode.equalsIgnoreCase("6"))
            morse = "-....";
        if (toEncode.equalsIgnoreCase("7"))
            morse = "--...";
        if (toEncode.equalsIgnoreCase("8"))
            morse = "---..";
        if (toEncode.equalsIgnoreCase("9"))
            morse = "----.";
        if (toEncode.equalsIgnoreCase("."))
            morse = ".-.-";
        if (toEncode.equalsIgnoreCase(","))
            morse = "--..--";
        if (toEncode.equalsIgnoreCase("?"))
            morse = "..--..";

        return morse;
    }
}

PlaySound 播放声音

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;


public class playSound 
{

    public playSound(){}

    public void playBlip() throws UnsupportedAudioFileException, IOException, LineUnavailableException
    {

        File soundFile = new File("blip.wav");
        AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

        DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
        Clip clip = (Clip) AudioSystem.getLine(info);
        clip.open(sound);

        clip.addLineListener( new LineListener() 
        {
            public void update(LineEvent event) 
            {
                if (event.getType() == LineEvent.Type.STOP) 
                {
                    event.getLine().close();
                    System.exit(0);
                }
            }
        });

        clip.start();
        clip.drain();
        clip.close();
    }
    public int getSoundDurationForThreadWait() throws UnsupportedAudioFileException, IOException, LineUnavailableException
    {
        File soundFile = new File("blip.wav");
        AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

        DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
        Clip clip = (Clip) AudioSystem.getLine(info);
        clip.open(sound);

        //making this method return milliseconds since threads waits are in this unit
        return (int) (clip.getMicrosecondLength()/1000);

    }
}        

Problem Program only plays sound one time. 问题程序只播放一次声音。 I suspect there is a threading blocking problem. 我怀疑存在线程阻塞问题。

Desired Results: 期望的结果:

Enter phrase: Hello 输入短语:Hello

audio plays as you would expect for a morse code 音频播放正如您对莫尔斯电码的期望一样

The specific problem is that your playBlip() method is designed to terminate the entire program when it reaches the end of the sound clip: 具体问题是你的playBlip()方法设计用于在声音片段结束时终止整个程序:

        clip.addLineListener( new LineListener() 
        {
            public void update(LineEvent event) 
            {
                if (event.getType() == LineEvent.Type.STOP) 
                {
                    event.getLine().close();
                    System.exit(0); // <------------ terminate the JVM
                }
            }
        });

But overall, I think you should examine your approach more closely; 但总的来说,我认为你应该更仔细地研究你的方法; you have a lot of code that seems to serve no purpose besides obfuscation. 除了混淆之外,你有很多代码似乎没有用处。 For example, you have two Thread instances, main and sound , that are designed to do absolutely nothing: calling main.start() will launch a new thread that exits immediately. 例如,你有两个Thread实例, mainsound ,它们被设计成绝对没有:调用main.start()将启动一个立即退出的新线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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