简体   繁体   中英

how to send .wav audio files using socket and serversocket class in java

File wavFile=new File("D:\\RecordAudio.wav");
FileInputStream fis=new FileInputStream(wavFile);
fis.read(tempBuffer, 0, cnt);
System.out.println(tempBuffer.length);

String byteArrayStr= new String(tempBuffer);

String rec=list1;
System.out.println(rec);

 String format="<"+rec+">-"+name+":"+byteArrayStr;

        pw.println(format);

    }
    catch(Exception e)
    {
                System.out.println("hello user12");
        System.out.println(e);
                    e.printStackTrace();
    }

//Actually i have picked my .wav file frmom pc and i want to send it to server using serversocket exception class and then server again send my file to particular client.So for this purpose i think we need to convert into bytearrayoutputstream. but my program not working properly

The following is something managed to pull together through researching and piecing code together regarding sending WAV files and saving them as WAV upon recieving them. I don't take credit for all the code

NOTE: not all WAV files will work since not all formats are supported by JAVA, you can convert them to a more generic format using a tool like wavosaur. check this answer fo more explanation https://stackoverflow.com/a/14961460/2225628 I have tested with a 21 MB file and it worked.

(code can use improvements for the time being it serves the goal)

Run Server then Client

Client:

import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

public class Client {

    private static Socket socket;
    private static BufferedInputStream inputStream;


    public static void main(String[] args) throws LineUnavailableException {
        
        try {
            socket = new Socket("127.0.0.1", 6666);

            if (socket.isConnected()) {

                inputStream = new BufferedInputStream(socket.getInputStream());


                AudioInputStream ais = AudioSystem.getAudioInputStream(inputStream);
                try {
                    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new
                            File("test3.wav")
                    );
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
                /*// IF YOU WANT TO PLAY SOUND DIRECTLY FROM SPEAKERS COMMENT OUT THE TRY CATCH BLOCK ABOVE
                //  AND UNCOMMENT THE BELOW SECTION
                Clip clip = AudioSystem.getClip();
                clip.open(ais);
                clip.start();

                while (inputStream != null) {
                    if (clip.isActive()) {

                        System.out.println("********** Buffred *********" + inputStream.available());

                    }
                }*/


            }

        } catch (IOException | UnsupportedAudioFileException e) {
            System.err.println(e);
        }
    }
}

Server:

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.File;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {


        try {
            ServerSocket serverSocker = new ServerSocket();
            Socket client = null;
            serverSocker.bind(new InetSocketAddress(6666));
            if (serverSocker.isBound()) {
                client = serverSocker.accept();
                OutputStream out = client.getOutputStream();
                while (true) {
                    AudioInputStream ain = testPlay("idont.wav");
                    if (ain != null) {
                        AudioSystem.write(ain, AudioFileFormat.Type.WAVE, out);
                    }
                }
            }
            serverSocker.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static AudioInputStream testPlay(String filename) {
        AudioInputStream din = null;
        try {
            File file = new File(filename);
            AudioInputStream in = AudioSystem.getAudioInputStream(file);
            System.out.println("Before :: " + in.available());

            AudioFormat baseFormat = in.getFormat();
            AudioFormat decodedFormat =
                    new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED, baseFormat.getSampleRate(),
                            8, baseFormat.getChannels(), baseFormat.getChannels(),
                            baseFormat.getSampleRate(), false);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            System.out.println("After :: " + din.available());
            return din;
        } catch (Exception e) {
            // Handle exception.
            e.printStackTrace();
        }
        return din;
    }
}

Again I do not take credit for writing the code I just pieced stuff together

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM