DariusSmif
DariusSmif

Reputation: 11

Sending a buzz sound to ear-bud left or right

Is there a way to write android java code, for an android phone, to send a buzz sound (i'm thinking a certain frequency) through the ear-phone jack and into earbuds left and right independently of one another. Basically I want to send a buzz to the left ear-bud. And i want to send a buzz to the right ear-bud.

Upvotes: 1

Views: 1981

Answers (1)

Kenny
Kenny

Reputation: 5542

This was quite an interesting question so i though i'd give it a go, i've written a class that generates a tone at a required frequency then plays it, i couldnt test the left/right volume part because i cant find my headphones but it should work!

Hope this helps!

Kenny

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class ToneGen {

    int seconds;
    int sampleRate = 16000;
    double frequency;
    double RAD = 2.0 * Math.PI;
    AudioTrack aTrack;

    /**
     * @param frequency The frequency of the tone
     * @param duration The duration of the tone in seconds
     * @param leftVolume Left volume 0.0f - silent, 1.0f full volume
     * @param rightVolume Right volume 0.0f - silent, 1.0f full volume
     */
    public ToneGen(double frequency, int duration, float leftVolume, float rightVolume){
        this.frequency = frequency;
        seconds = duration * 2;

        byte[] buffer = new byte[sampleRate * seconds];
        for ( int i=0; i<buffer.length; i++ )
        {
            buffer[i] = (byte)( Math.sin( RAD * frequency / sampleRate * i ) * 127.0 );
        }

        aTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
            sampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
            AudioFormat.ENCODING_PCM_16BIT,
            buffer.length, AudioTrack.MODE_STATIC);
        aTrack.setStereoVolume(leftVolume, rightVolume);
        aTrack.write(buffer, 0, buffer.length);

    }

    public void Play(){
        aTrack.play();
    }

    public void Stop(){
        aTrack.stop();
    }
}

Upvotes: 1

Related Questions