在Java中的音频工作 [英] Working with audio in Java

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

问题描述

我去了Java的声音上的教程,但不知它的方式对于初学者过于复杂。结果
这是这里结果
我的目标是这样的:

  • 检测所有音频输入和输出设备

  • 让用户选择一个音频的输入设备

  • 捕获用户说什么

  • 它输出到默认音频输出设备
  • 现在我怎么去这样做?结果
    有没有一个更好的教程?结果
    我曾尝试:

     进口javax.sound.sampled中*。
    公共类SoundTrial {
        公共静态无效的主要(字串[] args){
            Mixer.Info []信息= AudioSystem.getMixerInfo();
            INT I = 0;
            对于(Mixer.Info打印:信息){            的System.out.println(姓名:+ I ++ print.getName());
                我++;
            }
        }
    }

    输出:

     名称:0主声音驱动程序
    名称:1扬声器和耳机(IDT高清晰度音频codeC)
    名称:2个独立耳机(IDT高清晰度音频codeC
    名称:3 SPDIF(数字输出通过HP扩展坞)(IDT高清晰度音频codeC)
    名称:4主声音捕获驱动程序
    名称:5集成麦克风阵列(ID
    名称:6麦克风(IDT高清晰度
    名称:7立体声混音(IDT高清晰度
    名称:8端口扬声器和耳机(IDT喜
    名称:9港口SPDIF(数字输出通过HP扩展坞)
    名称:10端口集成麦克风阵列(ID
    名称:11端口麦克风(IDT高清晰度
    名称:12端口立体声混音(IDT高清晰度
    名称:13端口独立耳机(IDT喜


    解决方案

    这code可以帮助你。请注意,这已经从该所链接:<一个href=\"http://www.java2s.com/$c$c/Java/2D-Graphics-GUI/CaptureaudioorvideothroughdevicesconnectedtothePC.htm\"相对=nofollow>音频视频的。我发现使用谷歌搜索,我刚刚张贴code在这里情形链路变为过时了。

    进口javax.media *。
    导入javax.media.format *。
    导入javax.media.protocol *。
    进口的java.util。*;/ ******************* ******************************
     *一个简单的应用程序,允许用户通过捕捉设备的音频或视频
     *连接到PC。通过命令行参数的用户指定是否
     *音频(-A)或视频(-v)捕获,捕获(-d)的持续时间
     *秒,写入媒体文件(-f)。
     *
     *应用程序将更为快捷方便,如果它提供的控制
     *在捕获以及内容类型的音频和视频的格式
     *输出。
     *
     *为捕捉设备的类搜索,支持特定的默认
     *曲目格式:音频和的Cinepak视频线性的。作为一个秋天,背面有两个
     *设备名称是硬coded到应用程序的一个例子如何
     *获得DeviceInfo当设备的名称是已知的。用户可以强制
     *应用程序使用-k(已知设备)标志使用这些名称。
     *
     *类是静态的,而是采用了较早的Location2Location例子
     *执行所有的处理器和数据接收器的相关工作。因此,应用
     *主要涉及CaptureDevice相关的操作。
     *
     * @author迈克尔(穗)巴洛
     ************************************************** ************ /
    公共类SimpleRecorder {  ////////////////////////////////////////////////// ///////////
      //为对音频和视频捕获设备名称
      //笔者的系统。这些将改变系统的系统,但有
      //仅作为备用。
      ////////////////////////////////////////////////// ///////////
      私有静态最后弦乐AUDIO_DEVICE_NAME =DirectSoundCapture;  私有静态最后弦乐VIDEO_DEVICE_NAME =VFW:微软WDM图像捕捉:0;  ////////////////////////////////////////////////// /////////
      //为文件的默认名称写的输出为
      //在那里它们被不是由用户与供应的情况。
      ////////////////////////////////////////////////// ////////
      私有静态最后弦乐DEFAULT_AUDIO_NAME =文件://./captured.wav;  私有静态最后弦乐DEFAULT_VIDEO_NAME =文件://./captured.avi;  ///////////////////////////////////////////
      //由用户请求的捕获的类型。
      //////////////////////////////////////////
      私有静态最后弦乐AUDIO =音频;  私有静态最后弦乐VIDEO =视频;  私有静态最后弦乐BOTH =音视频;  ////////////////////////////////////////////////// //////////////////
      //唯一的音频和视频格式的特定应用
      //支持。一个更好的方案将允许格式的用户选择
      //但将增长近的小例子大小。
      ////////////////////////////////////////////////// //////////////////
      私有静态最终格式AUDIO_FORMAT =新AudioFormat的(
          AudioFormat.LINEAR);  私有静态最终格式VIDEO_FORMAT =新VideoFormat(
          VideoFormat.CINEPAK);  公共静态无效的主要(字串[] args){    ////////////////////////////////////////////////// ////
        //对象来处理加工和下沉
        //从装置捕获的数据。
        ////////////////////////////////////////////////// ////
        Location2Location捕获;    /////////////////////////////////////
        //音频和视频捕获设备。
        ////////////////////////////////////
        的CaptureDeviceInfo audioDevice = NULL;
        的CaptureDeviceInfo videoDevice = NULL;    ////////////////////////////////////////////////// ///////////
        //捕获设备的位置加的名称和位置
        //目的地。
        ////////////////////////////////////////////////// ///////////
        MediaLocator的captureLocation = NULL;
        的MediaLocator destinationLocation;
        字符串destinationName = NULL;    ////////////////////////////////////////////////// //////////
        //格式化处理器(在Location2Location)必须匹配。
        ////////////////////////////////////////////////// //////////
        格式[] =格式新业态[1];    ///////////////////////////////////////////////
        //内容类型为音频或视频捕获。
        //////////////////////////////////////////////
        ContentDescriptor audioContainer =新ContentDescriptor(
            FileTypeDescriptor.WAVE);
        ContentDescriptor videoContainer =新ContentDescriptor(
            FileTypeDescriptor.MSVIDEO);
        ContentDescriptor容器= NULL;    ////////////////////////////////////////////////// //////////////////
        //记录(以秒为单位)的持续时间和周期等之后
        ////////////////////////////////////////////////// /////////////////
        双时间= 10;
        INT WAITFOR = 0;    //////////////////////////
        //音频或视频捕获?
        //////////////////////////
        字符串选择= AUDIO;    ////////////////////////////////////////////////// //////
        //支持有问题的格式的所有设备。
        //保的手段程序适用于不同的
        //用不同的捕获设备的机器。
        ////////////////////////////////////////////////// //////
        矢量装置;    ////////////////////////////////////////////////// ////////
        //是否搜索支持捕获设备
        //格式或使用的设备卫生组织名是已经
        //已知的应用程序。
        ////////////////////////////////////////////////// ////////
        布尔useKnownDevices = FALSE;    ////////////////////////////////////////////////// ///////
        //进程的命令行选项,以音频或视频,
        //持续时间,以及文件保存到。
        ////////////////////////////////////////////////// ///////
        的for(int i = 0;!我0 && useKnownDevices){
            audioDevice =(的CaptureDeviceInfo)devices.elementAt(0);
          }其他
            audioDevice = CaptureDeviceManager.getDevice(AUDIO_DEVICE_NAME);
          如果(audioDevice == NULL){
            的System.out.println(找不到合适的音频设备退出。);
            System.exit(1);
          }
          captureLocation = audioDevice.getLocator();
          格式[0] = AUDIO_FORMAT;
          如果(destinationName == NULL)
            destinationName = DEFAULT_AUDIO_NAME;
          容器= audioContainer;
        }
        ////////////////////////////////////////////////// ///////////////
        //视频拍摄进行设置。包括寻找合适的
        //设备,obatining其的MediaLocator和设置内容
        //类型。
        ////////////////////////////////////////////////// //////////////
        否则如果(selected.equals(视频)){
          设备= CaptureDeviceManager.getDeviceList(VIDEO_FORMAT);
          如果(devices.size()> 0 &&!useKnownDevices)
            videoDevice =(的CaptureDeviceInfo)devices.elementAt(0);
          其他
            videoDevice = CaptureDeviceManager.getDevice(VIDEO_DEVICE_NAME);
          如果(videoDevice == NULL){
            的System.out.println(找不到合适的视频设备退出);
            System.exit(1);
          }
          captureLocation = videoDevice.getLocator();
          格式[0] = VIDEO_FORMAT;
          如果(destinationName == NULL)
            destinationName = DEFAULT_VIDEO_NAME;
          容器= videoContainer;
        }否则如果(selected.equals(BOTH)){
          captureLocation = NULL;
          格式=新业态[2];
          格式[0] = AUDIO_FORMAT;
          格式[1] = VIDEO_FORMAT;
          容器= videoContainer;
          如果(destinationName == NULL)
            destinationName = DEFAULT_VIDEO_NAME;
        }    ////////////////////////////////////////////////// //////////////////
        //执行所有必需的处理器和数据接收器preparation通过
        //将Location2Location类。
        ////////////////////////////////////////////////// //////////////////
        destinationLocation =新的MediaLocator(destinationName);
        的System.out.println(配置捕获请等待。);
        捕获=新Location2Location(captureLocation,destinationLocation,
            格式,容器,1.0);    ////////////////////////////////////////////////// ///////////////////////////
        //开始录制,并告知用户。指定的长度
        //记录。然后等待周围的高达4倍的持续时间
        //记录
        //(可能需要更长的时间下沉/写入数据所以要等一会柜面)。
        ////////////////////////////////////////////////// ///////////////////////////
        的System.out.println(开始录制+时间+秒
            +选择+...);
        capture.setStopTime(新时代(持续时间));
        如果(WAITFOR == 0)
          WAITFOR =(INT)(4000 *持续时间);
        其他
          WAITFOR * = 1000;
        INT等待= capture.transfer(WAITFOR);    ////////////////////////////////////////////////// ///////
        //在记录的成功(或其他方式)的报告。
        ////////////////////////////////////////////////// ///////
        INT状态= capture.getState();
        如果(状态== Location2Location.FINISHED)
          的System.out.println(选择
              +成功捕获约
              +((int)的((等待+500)/ 1000))
              +秒的数据写入。+ destinationName);
        否则,如果(状态== Location2Location.FAILED)
          的System.out.println(选择
              +捕获后约失败
              +((int)的((等待+500)/ 1000))+秒);
        其他{
          的System.out.println(选择
              +捕捉仍然大约持续后
              +((int)的((等待+500)/ 1000))+秒);
          的System.out.println(过程可能失败);
        }    System.exit(0);
      }
    }

    I went over Java's tutorial on sounds but somehow it is way too complex for a beginner.
    It is here
    My aim is this:

  • Detect all the audio input and output devices
  • let the user select a audio input device
  • capture what the user says
  • output it to the default audio output device
  • Now how do I go about doing that?
    Is there a better tutorial available?
    What I have tried:

    import javax.sound.sampled.*;
    public class SoundTrial {
        public static void main(String[] args) {
            Mixer.Info[] info = AudioSystem.getMixerInfo();
            int i =0;
            for(Mixer.Info print : info){
    
                System.out.println("Name: "+ i + " " + print.getName());
                i++;
            }
        }
    }  
    

    output:

    Name: 0 Primary Sound Driver
    Name: 1 Speakers and Headphones (IDT High Definition Audio CODEC)
    Name: 2 Independent Headphones (IDT High Definition Audio CODEC
    Name: 3 SPDIF (Digital Out via HP Dock) (IDT High Definition Audio CODEC)
    Name: 4 Primary Sound Capture Driver
    Name: 5 Integrated Microphone Array (ID
    Name: 6 Microphone (IDT High Definition
    Name: 7 Stereo Mix (IDT High Definition
    Name: 8 Port Speakers and Headphones (IDT Hi
    Name: 9 Port SPDIF (Digital Out via HP Dock)
    Name: 10 Port Integrated Microphone Array (ID
    Name: 11 Port Microphone (IDT High Definition
    Name: 12 Port Stereo Mix (IDT High Definition
    Name: 13 Port Independent Headphones (IDT Hi
    

    解决方案

    This code may help you. Note this has been taken from this link: Audio Video. I found using Google search, I just posted code here in-case link becomes outdated.

    
    import javax.media.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import java.util.*;
    
    /*******************************************************************************
     * A simple application to allow users to capture audio or video through devices
     * connected to the PC. Via command-line arguments the user specifies whether
     * audio (-a) or video (-v) capture, the duration of the capture (-d) in
     * seconds, and the file to write the media to (-f).
     * 
     * The application would be far more useful and versatile if it provided control
     * over the formats of the audio and video captured as well as the content type
     * of the output.
     * 
     * The class searches for capture devices that support the particular default
     * track formats: linear for audio and Cinepak for video. As a fall-back two
     * device names are hard-coded into the application as an example of how to
     * obtain DeviceInfo when a device's name is known. The user may force the
     * application to use these names by using the -k (known devices) flag.
     * 
     * The class is static but employs the earlier Location2Location example to
     * perform all the Processor and DataSink related work. Thus the application
     * chiefly involves CaptureDevice related operations.
     * 
     * @author Michael (Spike) Barlow
     ******************************************************************************/
    public class SimpleRecorder {
    
      /////////////////////////////////////////////////////////////
      // Names for the audio and video capture devices on the
      // author's system. These will vary system to system but are
      // only used as a fallback.
      /////////////////////////////////////////////////////////////
      private static final String AUDIO_DEVICE_NAME = "DirectSoundCapture";
    
      private static final String VIDEO_DEVICE_NAME = "vfw:Microsoft WDM Image Capture:0";
    
      ///////////////////////////////////////////////////////////
      // Default names for the files to write the output to for
      // the case where they are not supplie by the user.
      //////////////////////////////////////////////////////////
      private static final String DEFAULT_AUDIO_NAME = "file://./captured.wav";
    
      private static final String DEFAULT_VIDEO_NAME = "file://./captured.avi";
    
      ///////////////////////////////////////////
      // Type of capture requested by the user.
      //////////////////////////////////////////
      private static final String AUDIO = "audio";
    
      private static final String VIDEO = "video";
    
      private static final String BOTH = "audio and video";
    
      ////////////////////////////////////////////////////////////////////
      // The only audio and video formats that the particular application
      // supports. A better program would allow user selection of formats
      // but would grow past the small example size.
      ////////////////////////////////////////////////////////////////////
      private static final Format AUDIO_FORMAT = new AudioFormat(
          AudioFormat.LINEAR);
    
      private static final Format VIDEO_FORMAT = new VideoFormat(
          VideoFormat.CINEPAK);
    
      public static void main(String[] args) {
    
        //////////////////////////////////////////////////////
        // Object to handle the processing and sinking of the
        // data captured from the device.
        //////////////////////////////////////////////////////
        Location2Location capture;
    
        /////////////////////////////////////
        // Audio and video capture devices.
        ////////////////////////////////////
        CaptureDeviceInfo audioDevice = null;
        CaptureDeviceInfo videoDevice = null;
    
        /////////////////////////////////////////////////////////////
        // Capture device's "location" plus the name and location of
        // the destination.
        /////////////////////////////////////////////////////////////
        MediaLocator captureLocation = null;
        MediaLocator destinationLocation;
        String destinationName = null;
    
        ////////////////////////////////////////////////////////////
        // Formats the Processor (in Location2Location) must match.
        ////////////////////////////////////////////////////////////
        Format[] formats = new Format[1];
    
        ///////////////////////////////////////////////
        // Content type for an audio or video capture.
        //////////////////////////////////////////////
        ContentDescriptor audioContainer = new ContentDescriptor(
            FileTypeDescriptor.WAVE);
        ContentDescriptor videoContainer = new ContentDescriptor(
            FileTypeDescriptor.MSVIDEO);
        ContentDescriptor container = null;
    
        ////////////////////////////////////////////////////////////////////
        // Duration of recording (in seconds) and period to wait afterwards
        ///////////////////////////////////////////////////////////////////
        double duration = 10;
        int waitFor = 0;
    
        //////////////////////////
        // Audio or video capture?
        //////////////////////////
        String selected = AUDIO;
    
        ////////////////////////////////////////////////////////
        // All devices that support the format in question.
        // A means of "ensuring" the program works on different
        // machines with different capture devices.
        ////////////////////////////////////////////////////////
        Vector devices;
    
        //////////////////////////////////////////////////////////
        // Whether to search for capture devices that support the
        // format or use the devices whos names are already
        // known to the application.
        //////////////////////////////////////////////////////////
        boolean useKnownDevices = false;
    
        /////////////////////////////////////////////////////////
        // Process the command-line options as to audio or video,
        // duration, and file to save to.
        /////////////////////////////////////////////////////////
        for (int i = 0; i  0 && !useKnownDevices) {
            audioDevice = (CaptureDeviceInfo) devices.elementAt(0);
          } else
            audioDevice = CaptureDeviceManager.getDevice(AUDIO_DEVICE_NAME);
          if (audioDevice == null) {
            System.out.println("Can't find suitable audio device. Exiting");
            System.exit(1);
          }
          captureLocation = audioDevice.getLocator();
          formats[0] = AUDIO_FORMAT;
          if (destinationName == null)
            destinationName = DEFAULT_AUDIO_NAME;
          container = audioContainer;
        }
        /////////////////////////////////////////////////////////////////
        // Perform setup for video capture. Includes finding a suitable
        // device, obatining its MediaLocator and setting the content
        // type.
        ////////////////////////////////////////////////////////////////
        else if (selected.equals(VIDEO)) {
          devices = CaptureDeviceManager.getDeviceList(VIDEO_FORMAT);
          if (devices.size() > 0 && !useKnownDevices)
            videoDevice = (CaptureDeviceInfo) devices.elementAt(0);
          else
            videoDevice = CaptureDeviceManager.getDevice(VIDEO_DEVICE_NAME);
          if (videoDevice == null) {
            System.out.println("Can't find suitable video device. Exiting");
            System.exit(1);
          }
          captureLocation = videoDevice.getLocator();
          formats[0] = VIDEO_FORMAT;
          if (destinationName == null)
            destinationName = DEFAULT_VIDEO_NAME;
          container = videoContainer;
        } else if (selected.equals(BOTH)) {
          captureLocation = null;
          formats = new Format[2];
          formats[0] = AUDIO_FORMAT;
          formats[1] = VIDEO_FORMAT;
          container = videoContainer;
          if (destinationName == null)
            destinationName = DEFAULT_VIDEO_NAME;
        }
    
        ////////////////////////////////////////////////////////////////////
        // Perform all the necessary Processor and DataSink preparation via
        // the Location2Location class.
        ////////////////////////////////////////////////////////////////////
        destinationLocation = new MediaLocator(destinationName);
        System.out.println("Configuring for capture. Please wait.");
        capture = new Location2Location(captureLocation, destinationLocation,
            formats, container, 1.0);
    
        /////////////////////////////////////////////////////////////////////////////
        // Start the recording and tell the user. Specify the length of the
        // recording. Then wait around for up to 4-times the duration of
        // recording
        // (can take longer to sink/write the data so should wait a bit incase).
        /////////////////////////////////////////////////////////////////////////////
        System.out.println("Started recording " + duration + " seconds of "
            + selected + " ...");
        capture.setStopTime(new Time(duration));
        if (waitFor == 0)
          waitFor = (int) (4000 * duration);
        else
          waitFor *= 1000;
        int waited = capture.transfer(waitFor);
    
        /////////////////////////////////////////////////////////
        // Report on the success (or otherwise) of the recording.
        /////////////////////////////////////////////////////////
        int state = capture.getState();
        if (state == Location2Location.FINISHED)
          System.out.println(selected
              + " capture successful in approximately "
              + ((int) ((waited + 500) / 1000))
              + " seconds. Data written to " + destinationName);
        else if (state == Location2Location.FAILED)
          System.out.println(selected
              + " capture failed after approximately "
              + ((int) ((waited + 500) / 1000)) + " seconds");
        else {
          System.out.println(selected
              + " capture still ongoing after approximately "
              + ((int) ((waited + 500) / 1000)) + " seconds");
          System.out.println("Process likely to have failed");
        }
    
        System.exit(0);
      }
    }
    
    

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

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