简体   繁体   English

声音在Java中不起作用

[英]Sound not working in Java

I've been researching sound files in Java for the past couple of days and I thought I finally could try and get some sound running. 在过去的几天中,我一直在研究Java中的声音文件,我认为我终于可以尝试使声音运行起来。

I coded a small segment but unfortunately, there is no sound be played after running it. 我编码了一小段,但是不幸的是,运行它之后没有声音播放。
Is there a bug somewhere that I'm not seeing or does this code not work. 我没有看到某个错误的地方,或者此代码不起作用。 Thanks. 谢谢。

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;

public class driver {
    public static void main ( String [] args ) throws Exception {
        URL resourceUrl = new URL("file:;///C:/Users/Jack/Desktop/Pok/pokemon.wav");
        final AudioClip clip = Applet.newAudioClip(resourceUrl);
        clip.loop();
    }
}

Let's start with... 让我们从...开始

URL resourceUrl = new URL("file:;///C:/Users/Jack/Desktop/Pok/pokemon.wav");

Apart from the fact that there is a ; 除了有一个事实; in the path which doesn't belong, there is a simpler way to generate a URL from a File 在不属于该路径的路径中,有一种更简单的方法可以从File生成URL

URL url = new File("C:/Users/Jack/Desktop/Pok/pokemon.wav").toURI().toURL();

Then move onto this... 然后继续前进...

final AudioClip clip = Applet.newAudioClip(resourceUrl);

Looking at your code, you program isn't an applet, so you really shouldn't be using Applet based methods. 查看您的代码,您的程序不是applet,因此您实际上不应该使用基于Applet的方法。

For better ways, start by taking a look at Sound Tutorial 为了获得更好的方法,请先看一下声音教程

Which might look something more like... 看起来更像是...

URL url = new File("C:/Users/Jack/Desktop/Pok/pokemon.wav").toURI().toURL();
AudioInputStream ais = AudioSystem.getAudioInputStream(url));
Clip clip = AudioSystem.getClip();
clip.open(ais);
clip.start();
clip.drain(); // Stop the main thread from exiting

This is the correct method to Open an audio clip: 这是打开音频剪辑的正确方法:

 public SoundClipTest() { try { URL url = this.getClass().getClassLoader().getResource("pokemon.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } } 

Well I think there's something wrong with your url, but not sure. 好吧,我认为您的网址有问题,但不确定。 However you could try this to play a sound: 但是,您可以尝试以下方法来播放声音:

String mySound = "pokemon.wav";
Media media = new Media(mySound);
MediaPlayer mp = new MediaPlayer(media);
mp.play();

You should have pokemon.wav in the same folder where your java file is. 您应该在java文件所在的文件夹中有pokemon.wav。

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

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