1

我使用以下代码从 Web 服务器上的 wav 文件中获取数据。、和读取字节getFormat(),每个执行一次 http 访问,服务器日志显示有 3 次访问。有没有办法让它一次旅行?getFormatLength()totallength

try {
    audioInputStream = AudioSystem.getAudioInputStream(url);//soundFile);
    format = audioInputStream.getFormat();
    totallength = audioInputStream.getFrameLength()*format.getFrameSize();
    waveData = new byte[(int)totallength];
    int total=0;
    int nBytesRead = 0;
    try {
        while (nBytesRead != -1 && total<totallength) {
            nBytesRead = audioInputStream.read(waveData, total, (int) totallength);
            if (nBytesRead>0)
                total+=nBytesRead;
            }
    ...
4

1 回答 1

1

看起来您首先将整个文件读入内存,为什么不先读入所有内容。

    // Read the audio file into waveData:
    BufferedInputStream in = new BufferedInputStream(url.openStream());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (;;) {
        int b = in.read();
        if (b == -1) {
            break;
        }
        bos.write(b);
    }
    in.close();
    bos.close();
    byte[] waveData = bos.toByteArray();

    // Create the AudioInputSteam:
    ByteArrayInputStream bis = new ByteArrayInputStream(waveData);
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bis);
于 2013-01-12T22:56:04.833 回答