1

I am trying to play a signal saved on a byte array, using javax.sound.sampled.SourceDataLine. I am trying for a start to play a simple sine wave. For some frequencies (for instances 1000Hz, 400Hz) it works well, but for others (1001, 440) I am only getting an almost pitchless buzz. The sampling rate is definitly high enough to prevent aliasing (16Khz). Any ideas ? Cheers.

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;

public class Player
{

    private static float SAMPLE_RATE = 16000;

    public static void main(String[] args)
    {
        playSound();
    }


    private static void playSound()
    {
        try
        {
            final AudioFormat audioFormat = new AudioFormat( SAMPLE_RATE, 8, 1, true,  true );
            SourceDataLine line = AudioSystem.getSourceDataLine( audioFormat );
            line.open( audioFormat );
            line.start();
        /* the last argument here is the frequency in Hz. works well with 1000, but with 1001 I get week and pitchless clicking sound sound*/
            byte[] signal = smpSin( 1, 1, 1000 );
            play( line, signal );
            line.drain();
            line.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    private static byte[] smpSin(double lenInSec, double amp, double signalFreq)
    {
        int len = (int)(SAMPLE_RATE * lenInSec);
        byte[] out = new byte[len];
        for (int i = 0; i < out.length; i++)
        {
            out[i] = (byte)(amp * Math.sin( ((2.0 * Math.PI * signalFreq) *  ((double)i)) / SAMPLE_RATE ));
        }
        return out;
    }

    private static void play(SourceDataLine line, byte[] array)
    {
        line.write( array, 0, array.length );
    }

}

Tadas S
  • 1,955
  • 19
  • 33
oded wolff
  • 147
  • 8

1 Answers1

0

You aren't saving the phase of the sinewave between buffer calls. Thus any phase discontinuity will cause a buzz at the rate play() is called. Frequencies where there is no buzz just happen to end at your default beginning phase.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153