Java的API的声音不会与所有.WAV文件? [英] Java's sound API doesn't work with all .WAV files?

查看:197
本文介绍了Java的API的声音不会与所有.WAV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前遇到了麻烦与的javax.sound.sampled 库玩耍。这里的 MCV ,我用它来播放我的音乐文件code:

I am currently having trouble playing around with the javax.sound.sampled library. Here's the MCV code that I use to play my audio files:

import javax.sound.sampled.*;
import java.io.File;

public class Foo
{
    public static void main(String[] args)
    {
        try
        {
            File f = new File("alarm.wav");
            AudioInputStream ais = AudioSystem.getAudioInputStream(f);
            Clip clip = AudioSystem.getClip();

            clip.open(ais);
            clip.start();
        }
        catch (Exception e) {}
    }
}

这code有时会抛出 UnsupportedAudioFileException

This code will sometimes throw an UnsupportedAudioFileException.

基本上,我有5 .WAV文件,我知道是两袖清风,因为他们发挥完全正常,当我在我的音乐打开他们的播放软件。然而,Java程序只适用于他们的3。

甲骨文在这里提到这种文件格式的支持。我怎样才能确保我所有的.WAV文件是Java的API音频兼容?是否有打.WAV文件如果由于某种原因,他们没有合适的编码一个万无一失的方法?

Oracle mentions support for this file format here. How can I make sure that all of my .WAV files are compatible with Java's audio API? Is there a foolproof way of playing .WAV files if for some reason they do not have the appropriate encoding?

推荐答案

您可以使用以下code得到的支持的格式列表播放:

You can use the following code to get a list of the supported formats for playback:

static List<AudioFormat> getSupportedAudioFormats() {
    List<AudioFormat> result = new ArrayList<AudioFormat>();
    for(Line.Info info : AudioSystem.getSourceLineInfo(
            new Line.Info(SourceDataLine.class))) {
        if(info instanceof SourceDataLine.Info) {
            result.addAll(Arrays.asList(
                ((SourceDataLine.Info)info).getFormats()));
        }
    }
    return result;
}

AudioFormat.Encoding 列出了的javax.sound.sampled 支持的编码。

一个安全的WAV音频格式是在44100Hz 16位PCM。

A safe WAV audio format is 16-bit PCM at 44100Hz.

您可以发现一个特定的文件格式为:

You can discover the format of a particular file with:

File file = new File("path_to_file.wav");
AudioFormat fmt = AudioSystem.getAudioFileFormat(file).getFormat();

这将是一个略高于试图获得例如线条更加宽松,但它仍然会抛出如果WAV文件具有如MP3数据。 WAV文件是可以存储超过PCM编码,其中一些的javax.sound.sampled 通常不支持的容器。

This will be a little more lenient than trying to get a line for example, but it will still throw if the WAV file has e.g. mp3 data. A WAV file is a container that can store encodings beyond PCM, some of which javax.sound.sampled does not normally support.

这篇关于Java的API的声音不会与所有.WAV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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