麻烦在Java中播放wav [英] Trouble playing wav in Java

查看:121
本文介绍了麻烦在Java中播放wav的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试播放

PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame

文件描述 here(1)这里(2)

第一种方法有效,但我不想依赖 sun。* 东西。第二个导致只播放一些领先的帧,听起来更像是一个点击。因为我正在玩ByteArrayInputStream,所以不能成为IO问题。

The first approach works, but I don't want to depend on sun.* stuff. The second results in just some leading frames being played, that sounds more like a click. Can't be an IO issue as I'm playing from a ByteArrayInputStream.

Plz分享你为何会发生这种情况的想法。 TIA。

Plz share your ideas on why might this happen. TIA.

推荐答案

我不确定为什么你链接的第二种方法会启动另一个线程;我相信无论如何音频都将在自己的线程中播放。在剪辑完成播放之前,您的应用程序是否完成了问题?

I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;

private static void playClip(File clipFile) throws IOException, 
  UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
  class AudioListener implements LineListener {
    private boolean done = false;
    @Override public synchronized void update(LineEvent event) {
      Type eventType = event.getType();
      if (eventType == Type.STOP || eventType == Type.CLOSE) {
        done = true;
        notifyAll();
      }
    }
    public synchronized void waitUntilDone() throws InterruptedException {
      while (!done) { wait(); }
    }
  }
  AudioListener listener = new AudioListener();
  AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
  try {
    Clip clip = AudioSystem.getClip();
    clip.addLineListener(listener);
    clip.open(audioInputStream);
    try {
      clip.start();
      listener.waitUntilDone();
    } finally {
      clip.close();
    }
  } finally {
    audioInputStream.close();
  }
}

这篇关于麻烦在Java中播放wav的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆