Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java byte array play sound

Tags:

java

audio

I have a small program that reads from dataline mic to byte array I am not 100% sure it works but just by printing part of the array it seem to chang when am making a sound next to the mic:)

I like to play the sound back how do i play the data from the buffer(byte array to sound)??

 package mic; 
import javax.sound.sampled.*;

public class Mic extends Thread{
    boolean flag;
    TargetDataLine mic;
    byte[] buffer;
    AudioFormat format;

    public static void main(String[] args) {
       Mic a=new Mic();
       a.start();
    }
    @Override
    public void run()
    {
        flag=true;
        startMic();
        while(flag)
        {
            send();
        }
    }
    public void send()
    {
        try{
            mic.read(buffer,0,512);
            System.out.println("1. "+buffer[0]);
        }catch(Exception ex)
        {

        }
    }
    public void startMic()
    {
        try{
            format=new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,8000.0F,16,2,4,8000.0F,true);
            DataLine.Info info=new DataLine.Info(TargetDataLine.class,format);
            mic=(TargetDataLine)AudioSystem.getLine(info);
            mic.open();
            mic.start();
            buffer=new byte[512];
        }catch(Exception exx)
        {
            System.out.println("exx");
        }

    }
}

EDIT:
what i wanted to do in the end is send the byte array to other app and play right away
like live stream of a radio

like image 542
user1246950 Avatar asked Dec 27 '22 17:12

user1246950


2 Answers

A easy way to test the captured data is to save them into a file and load then in audacity using the RAW file import. Just specify your raw file format as : Sampling rate 8KHz format PCM big endian stereo 16 bits

like image 36
Julien Vermillard Avatar answered Jan 10 '23 11:01

Julien Vermillard


Based on this:

// Create the AudioData object from the byte array
AudioData audiodata = new AudioData(byteArray);
// Create an AudioDataStream to play back
AudioDataStream audioStream = new AudioDataStream(audioData);
// Play the sound
AudioPlayer.player.start(audioStream);
like image 104
kirbyfan64sos Avatar answered Jan 10 '23 09:01

kirbyfan64sos