在 Ubuntu Java 中定义 AudioFormat

Defining AudioFormat in Java on Ubuntu

我想知道如何在 Ubuntu 上定义剪辑的 AudioFormat。在 Windows 上,以下代码有效,但在 Ubuntu 14.10 上无效。

import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

class SongPlayer{    
    static int samplesPerSecond = 44100;

    // Plays back a raw audio buffer being passed.
    // @param song Raw signal of sound to be played. Amplitude in range [-1.0, 1.0]
    static void playSong(double[] song){
        AudioFormat format = new AudioFormat(
            Encoding.PCM_SIGNED,         // Encoding
            samplesPerSecond,            // sample rate
            Short.SIZE,                  // bits per sample
            1,                           // number of channels
            Short.SIZE / 8,              // bytes per frame
            samplesPerSecond,            // frame rate
            true);                       // big endian

        ByteBuffer buffer = ByteBuffer.allocate(song.length * (Short.SIZE / 8));
        ShortBuffer sb = buffer.asShortBuffer();
        for (double value : song){
            value = Math.max(-1.0,  Math.min(1.0, value));
            sb.put((short)(Short.MAX_VALUE * value));
        }

        AudioInputStream stream = new AudioInputStream(new ByteArrayInputStream(buffer.array()), format, song.length);

        try{
            Clip clip = AudioSystem.getClip();
            clip.open(stream);
            clip.start();
            Thread.sleep(1000 * 5);
            clip.drain();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("Playback failed!");
        }
    }

    public static void main(String[] args){
        double[] noise = new double[1000000];

        for(int i = 0; i < 1000000; i++){
            noise[i] = 2 * Math.random() - 1;
        }

        playSong(noise);
    }
}

错误信息如下:

    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.createStream(PulseAudioDataLine.java:142)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:99)
    at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:283)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:402)
    at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:453)
    at SongPlayer.playSong(song.java:39)
    at SongPlayer.main(song.java:56)
Playback failed!

通常,我会使用stream.getFormat()来获取格式,但在这种情况下,我想要"play a song" -1和1之间的随机数,这会导致随机噪声。我已经阅读了有关类似问题的问题,但他们通常只是想对文件进行操作,而这是不同的。感谢任何提供帮助的人!

不要在您的程序中使用 IcedTea JRE。我 运行 你在 ubuntu 上提供的代码来自 webupd8 ppa 的 Oracle Java 8;它有效。安装 Oracle Java 8 点赞

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer