Example usage for javax.sound.sampled AudioSystem getSourceDataLine

List of usage examples for javax.sound.sampled AudioSystem getSourceDataLine

Introduction

In this page you can find the example usage for javax.sound.sampled AudioSystem getSourceDataLine.

Prototype

public static SourceDataLine getSourceDataLine(AudioFormat format) throws LineUnavailableException 

Source Link

Document

Obtains a source data line that can be used for playing back audio data in the format specified by the AudioFormat object.

Usage

From source file:com.music.tools.ScaleTester.java

public static void main(String[] args) {
    System.out.println(//w ww. ja va2  s.c  o m
            "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>");
    final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true);
    try {
        fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class);
        int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class);

        List<Double> harmonicFrequencies = new ArrayList<>();
        List<String> ratios = new ArrayList<>();
        Set<Double> frequencies = new HashSet<Double>();
        frequencies.add(fundamentalFreq);
        int octaveMultiplier = 2;
        for (int i = 2; i < 100; i++) {
            // Exclude the 7th harmonic TODO exclude the 11th as well?
            // http://www.phy.mtu.edu/~suits/badnote.html
            if (i % 7 == 0) {
                continue;
            }
            double actualFreq = fundamentalFreq * i;
            double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier);
            if (closestTonicRatio < 1 || closestTonicRatio > 2) {
                octaveMultiplier *= 2;
            }
            double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier);
            double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic);

            harmonicFrequencies.add(actualFreq);
            frequencies.add(normalizedFreq);
            if (frequencies.size() == pitchesInChromaticScale) {
                break;
            }
        }

        System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies);
        System.out.println("Transposed harmonic frequencies: " + frequencies);

        List<Double> chromaticScale = new ArrayList<>(frequencies);
        Collections.sort(chromaticScale);

        // find the "perfect" interval (e.g. perfect fifth)
        int perfectIntervalIndex = 0;
        int idx = 0;
        for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) {
            Double noteFreq = it.next();
            long[] fraction = findCommonFraction(noteFreq / fundamentalFreq);
            fractionCache.put(noteFreq, fraction);
            if (fraction[0] == 3 && fraction[1] == 2) {
                perfectIntervalIndex = idx;
                System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex);
            }
            idx++;
            ratios.add(Arrays.toString(fraction));
        }
        System.out.println("Ratios to fundemental frequency: " + ratios);

        if (getBooleanArgument(args, 4, USE_ET)) {
            chromaticScale = temper(chromaticScale);
        }

        System.out.println();
        System.out.println("Chromatic scale: " + chromaticScale);

        Set<Double> scaleSet = new HashSet<Double>();
        scaleSet.add(chromaticScale.get(0));
        idx = 0;
        List<Double> orderedInCircle = new ArrayList<>();
        // now go around the circle of perfect intervals and put the notes
        // in order
        while (orderedInCircle.size() < chromaticScale.size()) {
            orderedInCircle.add(chromaticScale.get(idx));
            idx += perfectIntervalIndex;
            idx = idx % chromaticScale.size();
        }
        System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle);

        List<Double> scale = new ArrayList<Double>(scaleSet);
        int currentIdxInCircle = orderedInCircle.size() - 1; // start with
                                                             // the last
                                                             // note in the
                                                             // circle
        int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class);
        while (scale.size() < scaleSize) {
            double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size());
            if (!scale.contains(pitch)) {
                scale.add(pitch);
            }
            currentIdxInCircle++;
        }
        Collections.sort(scale);

        System.out.println("Scale: " + scale);

        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af);
        line.start();

        Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]);

        // first play the whole scale
        WaveMelodyGenerator.playScale(line, scaleFrequencies);
        // then generate a random melody in the scale
        WaveMelodyGenerator.playMelody(line, scaleFrequencies);

        line.drain();
        line.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.woz_dialog.ros_woz_dialog_project.TTSHTTPClient.java

public void synthesise(String utterance) throws Exception {

    try {//  w w w .j  a va 2s .c o m
        log.fine("calling Nuance server to synthesise utterance \"" + utterance + "\"");

        HttpPost httppost = new HttpPost(ttsURI);
        httppost.addHeader("Content-Type", "text/plain");
        httppost.addHeader("Accept", "audio/x-wav;codec=pcm;bit=16;rate=16000");
        HttpEntity entity = new StringEntity(utterance);

        //HttpEntity entity = new ByteArrayEntity(utterance.getBytes("UTF-8"));

        httppost.setEntity(entity);

        HttpResponse response = ttsClient.execute(httppost);

        HttpEntity resEntity = response.getEntity();

        if (resEntity == null || response.getStatusLine().getStatusCode() != 200) {
            System.out.println("Response status: " + response.getStatusLine());
            throw new Exception("Response status: " + response.getStatusLine());
        }

        format = new AudioFormat(16000, 16, 1, true, false);

        System.out.println(response.getStatusLine().getStatusCode());

        data = new byte[0];
        write(resEntity.getContent());
        httppost.releaseConnection();

        //Get the file path
        String basepath = System.getProperty("user.home");
        basepath = basepath + "/wav/" + LANGUAGE + "/" + VOICE;
        File dir = new File(basepath);

        if (!dir.exists()) {
            // attempt to create the directory here
            boolean successful = dir.mkdirs();
            if (successful) {
                // creating the directory succeeded
                System.out.println("directory was created successfully");
            } else {
                // creating the directory failed
                log.severe("failed trying to create the directory");
                throw new Exception("failed trying to create the directory");
            }

            return;

        }

        String fullpath = basepath + "/" + utterance.toLowerCase() + ".wav";

        //Record the sound
        generateFile(data, new File(fullpath));

        //Play the received sound

        SourceDataLine line = AudioSystem.getSourceDataLine(format);

        line.open(format);
        line.start();

        rewind();

        int nBytesRead = 0;
        byte[] abData = new byte[512 * 16];

        while (nBytesRead != -1) {
            nBytesRead = read(abData, 0, abData.length);

            if (nBytesRead >= 0) {
                line.write(abData, 0, nBytesRead);
            }
        }

        line.drain();
        if (line.isOpen()) {
            line.close();
        }

    } catch (LineUnavailableException e) {
        log.warning("Audio line is unavailable: " + e);
        throw e;
    } catch (Exception e) {
        throw e;
    }

}

From source file:net.sourceforge.subsonic.service.jukebox.AudioPlayer.java

public AudioPlayer(InputStream in, Listener listener) throws Exception {
    this.in = new BufferedInputStream(in);
    this.listener = listener;

    AudioFormat format = AudioSystem.getAudioFileFormat(this.in).getFormat();
    line = AudioSystem.getSourceDataLine(format);
    line.open(format);//from   w w  w  .j a  va2s  .  c  om
    LOG.debug("Opened line " + line);

    if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
        gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        setGain(0.5f);
    }
    new AudioDataWriter();
}

From source file:org.madsonic.service.jukebox.AudioPlayer.java

public AudioPlayer(InputStream in, Listener listener) throws Exception {
    this.in = new BufferedInputStream(in);
    this.listener = listener;

    AudioFormat format = AudioSystem.getAudioFileFormat(this.in).getFormat();
    line = AudioSystem.getSourceDataLine(format);
    line.open(format);/*from ww  w.  j  a va2  s .c o  m*/
    LOG.debug("Opened line " + line);

    if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
        gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        setGain(DEFAULT_GAIN);
    }
    new AudioDataWriter();
}