如何在4.0扬声器配置中使用Java播放单声道声音

时间:2015-02-22 18:41:45

标签: java audio javasound

我需要在Java中播放.wav单声道文件(可能在RAM中预加载)到4.0扬声器配置的所有扬声器。我还需要在播放音频时独立调整每个声道的音量,保持系统音量不变。

这是我目前的代码。它远远不是我需要的。 我怎样才能做到这一点?感谢。

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.Mixer;
import javax.sound.sampled.SourceDataLine;

public class AudioPlayer extends Thread {

    private final int BUFFER_SIZE = 128000;
    private File soundFile;
    private AudioInputStream audioStream;
    private AudioFormat audioFormat;
    private SourceDataLine sourceLine;
    String filename;
    Mixer mixer;

    public void load(String filename) {
        this.filename = filename;
    }

    public AudioPlayer() {
    }

    public void run() {
        try {
            soundFile = new File(filename);
            audioStream = AudioSystem.getAudioInputStream(soundFile);
            audioFormat = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
            sourceLine = (SourceDataLine) AudioSystem.getLine(info);
            sourceLine.open(audioFormat);
        } 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();
    }
}

0 个答案:

没有答案