如何使用 java 播放 .wav 文件

编程入门 行业动态 更新时间:2024-10-23 21:27:53
本文介绍了如何使用 java 播放 .wav 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 Java 播放 *.wav 文件.我希望它执行以下操作:按下按钮时,播放一声短促的哔声.

I am trying to play a *.wav file with Java. I want it to do the following: When a button is pressed, play a short beep sound.

我已经用谷歌搜索过了,但大部分代码都不起作用.有人可以给我一个简单的代码片段来播放 .wav 文件吗?

I have googled it, but most of the code wasn't working. Can someone give me a simple code snippet to play a .wav file?

推荐答案

最后我设法做到了以下,它工作正常

Finally I managed to do the following and it works fine

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; public class MakeSound { private final int BUFFER_SIZE = 128000; private File soundFile; private AudioInputStream audioStream; private AudioFormat audioFormat; private SourceDataLine sourceLine; /** * @param filename the name of the file that is going to be played */ public void playSound(String filename){ String strFilename = filename; try { soundFile = new File(strFilename); } catch (Exception e) { e.printStackTrace(); System.exit(1); } try { audioStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e){ e.printStackTrace(); System.exit(1); } audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sourceLine.start(); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { @SuppressWarnings("unused") int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); } } sourceLine.drain(); sourceLine.close(); } }

更多推荐

如何使用 java 播放 .wav 文件

本文发布于:2023-07-11 12:14:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1094019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文件   java   wav

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!