使用 try and catch 时播放声音

无法编译。我正在尝试在使用 try and catch 时播放声音。wav 文件位于我的桌面上。我收到错误消息,例如:AudioStream 无法解析为类型 AudioStream 无法解析为类型 AudioPlayer 无法解析。


我不确定如何解决这个问题,我知道它很简单,


import java.io.FileInputStream;

import java.io.InputStream;


public class PlayMySoundApplication

{

public static void main(String[] args) 

 throws Exception

{

// open the sound file as a Java input stream

String applause2x = "/Users/pc/Desktop/applause2x.wav";

InputStream in = new FileInputStream(applause2x);


// create an audiostream from the inputstream

AudioStream audioStream = new AudioStream(in);


// play the audio clip with the audioplayer class

AudioPlayer.player.start(audioStream);


慕慕森
浏览 132回答 2
2回答

幕布斯7119047

为音频添加导入,import java.io.*;import sun.audio.*;public class PlayMySoundApplication{  public static void main(String[] args)   throws Exception  {    // open the sound file as a Java input stream    String applause2x = "/Users/pc/Desktop/applause2x.wav";InputStream in = new FileInputStream(applause2x);    // create an audiostream from the inputstream    AudioStream audioStream = new AudioStream(in);    // play the audio clip with the audioplayer class    AudioPlayer.player.start(audioStream);  }}

宝慕林4294392

我不知道您要使用什么声音库。如果您使用的是不错的 JDK 版本,那应该可以解决问题:import java.io.File;import java.io.IOException;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.SourceDataLine;import javax.sound.sampled.UnsupportedAudioFileException;public class MakeSound {    public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException {        playSound("test.wav");    }    public static void playSound(String strFilename)            throws LineUnavailableException, UnsupportedAudioFileException, IOException {        File soundFile = new File(strFilename);        AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundFile);        AudioFormat audioFormat = audioStream.getFormat();        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);        try (SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);) {            sourceLine.open(audioFormat);            sourceLine.start();            int nBytesRead = 0;            byte[] abData = new byte[128000];            while (nBytesRead != -1) {                nBytesRead = audioStream.read(abData, 0, abData.length);                if (nBytesRead > 0) {                    sourceLine.write(abData, 0, nBytesRead);                }            }            sourceLine.drain();        }    }}!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java