Sound effects and music

Slides:



Advertisements
Similar presentations
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Advertisements

Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Referring to Java API Specifications
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Java Audio.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
Client/Server In Java An Introduction to TCP/IP and Sockets.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Practical Session 11 Multi Client-Server Java NIO.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
DBI Representation and Management of Data on the Internet.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
© Amir Kirsh Java Networking Written by Amir Kirsh.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Sound effects and music Java Sound API: javax.sound.sampled 8- or 16-bit samples from.
Java Sockets Programming
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Practical Session 12 Reactor Pattern. Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread.
Practical Session 11 Multi Client-Server Java NIO.
Java Server Programming Web Interface for Java Programs.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
© M. Winter COSC 3P40 – Advanced Object-Oriented Programming 10.1 Sound effects and music Java Sound API: javax.sound.sampled 8- or 16-bit samples from.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Advanced Java Session 4 - Extra New York University School of Continuing and Professional Studies.
SPL/2010 Reactor Design Pattern 1. SPL/2010 Overview ● blocking sockets - impact on server scalability. ● non-blocking IO in Java - java.niopackage ●
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Network Programming Communication between processes Many approaches:
Java 13. Networking public class SumTest {
Object-Orientated Analysis, Design and Programming
Stock Market Quotes – Socket Version
Threads in Java Two ways to start a thread
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Block 15 Developing the Calculator application
Beyond HTTP Up to this point we have been dealing with software tools that run on browsers and communicate to a server that generates files that can be.
NETWORK PROGRAMMING CNET 441
Networking with Java 2.
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
„Networking”.
Reactor Design Pattern
Clients and Servers 19-Nov-18.
UNIT-6.
Clients and Servers 1-Dec-18.
CPSC 441 UDP Socket Programming
Distributed Computing
Programming TCP Sockets
Socket Programming with UDP
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Thread per client and Java NIO
Presentation transcript:

Sound effects and music Java Sound API: javax.sound.sampled 8- or 16-bit samples from 8,000Hz to 48,000Hz mono or stereo sound file formats: AIFF, AU, WAV (Examples: 16-bit, mono, 44,100Hz, WAV)

Loading and playing a sound try { File file = new File(“…”); AudioInputStream stream = AudioSystem.getAudioInputStream(file); AudioFormat format = stream.getFormat(); } catch(Exception ex) { // IOException or UnsupportedAudioFileException } DataLine.Info info = new DataLine.Info(SourceDataLine.class,format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format,bufferSize); // LineUnavailableException

try { int numBytesRead = 0; while (numBytesRead != -1) { numBytesRead = stream.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } catch (Exception ex) { // IOException }; line.drain(); line.close();

Sound filter Examples: echo filter simulated 3D sound filter SoundFilter class (abstract class): filter(byte[] buffer, int offset, int length) – Filters an array of samples. getRemainingSize() – Gets the remaining size, in bytes, that this filter can play after the sound is finished. reset() – Resets the filter so that it can be used again on a different sound.

FilteredSoundStream public class FilteredSoundStream extends FilterInputStream { … public int read(byte[] samples, int offset, int length) throws IOException { int bytesRead = super.read(samples, offset, length); if (bytesRead > 0) { soundFilter.filter(samples, offset, bytesRead); return bytesRead; }; if (remainingSize == REMAINING_SIZE_UNKNOWN) { remainingSize = soundFilter.getRemainingSize(); remainingSize = remainingSize / 4 * 4;

if (remainingSize > 0) { length = Math.min(length, remainingSize); for (int i=offset; i<offset+length; i++) { samples[i] = 0; }; soundFilter.filter(samples, offset, length); remainingSize-=length; return length; } else { return -1; }

Echo filter Delay Original sound First echo Second echo delay: numbers of samples to delay (44,100Hz sound, 1 sec delay = 44,100 samples) decay: value from 0 to 1 0 means no echo 1 means the echo is the same volume as the original sound

Emulating 3D sound Many different effects are used to create 3D sounds. Make sound diminish with distance so the farther away a sound source is, the quieter it is. Pan sounds to the appropriate speaker. Apply room effects so sound waves bounce off walls, creating echoes and reverberation. Apply the Doppler effect so a sound source movement affect its pitch.

SoundManager The SoundManager class has the following features: provides a common interface for loading and playing sounds (including filters), extends the ThreadPool class, each thread in the thread pool has its own buffer and line object (thread-local variables).

Playing music Java Sound API provides MIDI sound capabilities in javax.sound.midi synthesizes MIDI music through the use of a soundbank, Java SDK includes a minimal-quality soundbank, higher-quality soundbanks from http://java.sun.com/products/java-media/sound/soundbanks.html To play MIDI music, you need two objects: Sequence object containing the data Sequencer sending the Sequence to the MIDI synthesizer

Sequence sequence = MidiSystem.getSequence(new File(“…”)); Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); sequencer.setSequence(sequence); sequencer.start(); Adding or taking away an instrument (track): sequencer.setTrackMute(trackNum, true);

Network programming Socket-based communication (java.net.*) server sockets (class ServerSocket) each server socket listens at a specific port the server must be running before its clients initiate contact after the sever socket is contacted by a client, a connection can be established constructor ServerSocket(int port) client sockets (class Socket) on the client side, constructors Socket(String host, int port) Socket(InetAddress address, int port) on the server side returned by the accept method of the server socket have an input and output stream

Example (Server) ... try { ServerSocket server = new ServerSocket(10997); while (running) { Socket client = server.accept(); InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream(); // handle the client in.close(); out.flush(); out.close(); client.close(); }; server.close(); } catch (Exception e) { e.printStackTrace();

Example (Client) ... try { Socket socket = new Socket(host,10997); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); // Send and receive data in.close(); out.flush(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); };

Network programming (cont’d) The server in the previous example handles one client at a time. just one client accepted at a time, operations on streams are blocking, Solution use multiple threads (one for each client)

Example (Server) ... try { ServerSocket server = new ServerSocket(10997); while (running) { Socket client = server.accept(); new ClientHandler(client).start(); }; server.close(); } catch (Exception e) { e.printStackTrace();

public class ClientHandler extends Thread { private Socket client; public ClientHandler(Socket client) { this.client = client; } public void run() { try { InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream(); ... // handle the client in.close(); out.flush(); out.close(); client.close(); } catch (Exception e) { e.printStackTrace(); };

Example public class ChatterServer { public static Vector clients = new Vector(); public static void main(String[] args) throws Exception { try { ServerSocket server = new ServerSocket(10997); while (true) { Socket client = server.accept(); ClientHandler clientHandler = new ClientHandler(client); clients.add(clientHandler); clientHandler.start(); }; } catch (Exception e) { e.printStackTrace(); }

Example public class ClientHandler extends Thread { private Socket client; private String clientName; private BufferedReader in; private PrintWriter out; public ClientHandler(Socket client) { this.client = client; try { in = new BufferedReader(new InputStreamReader( client.getInputStream())); out = new PrintWriter(new OutputStreamWriter( client.getOutputStream())); } catch (Exception e) { e.printStackTrace(); }; }

Example public String getClientName() { return clientName; } public synchronized void sendMessage(String msg) { if (out != null) { out.println(msg); out.flush(); }; public void broadcastMessage(String msg) { for(Iterator it = ChatterServer.clients.iterator(); it.hasNext();) { ClientHandler ch = (ClientHandler) it.next(); if (ch != this) ch.sendMessage(msg);

Example public void run() { if (in != null && out != null) { ... while (true) { String str = in.readLine(); if (str == null) break; if (str.trim().equals("BYE")) break; broadcastMessage("From " + clientName + ": " + str); }; broadcastMessage("User " + clientName + " has closed connection."); client.close(); ChatterServer.clients.remove(this); }

Class InetAddress This class represents internet addresses: InetAddress addr = InetAddress.getByName("sandcastle")); byte[] b = {(byte) 139, (byte)57, (byte)96, (byte)6}; InetAddress addr = InetAddress.getByAddress(b)

JDK 1.4 NIO Libraries Channels (java.nio.channels.*) Interfaces public void close(); public boolean isOpen(); ReadableByteChannel and WritableByteChannel public int read(ByteBuffer dst); public int write(ByteBuffer src); ByteChannel GatheringByteChannel and ScatteringByteChannel long write(ByteBuffer[] srcs); long write(ByteBuffer[] srcs, long offset, long length); long read(ByteBuffer[] dsts); long read(ByteBuffer[] dsts, long offset, long length);

NIO (cont.) Classes ServerSocketChannel ServerSocketChannel sSockChan; sSockChan = ServerSocketChannel.open(); sSockChan.configureBlocking(false); InetAddress addr = InetAddress.getLocalHost(); sSockChan.socket().bind(new InetSocketAddress(addr,PORT)); SocketChannel SocketChannel has all the methods of ServerSocketChannel methods for reading and writing methods for managing the connection

NIO (cont.) sSockChan.accept(); (server) SocketChannel.open(SocketAddress address); (client) or channel = SocketChannel.open(); channel.connect(SocketAddress address); DatagramChannel using UDP (User Datagram Protocol) instead of TCP UDP is an unreliable protocol.

NIO (cont.) Buffers Classes ByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer MappedByteBuffer methods for querying and manipulating the capacity, position, limit, and mark of the buffer 1 2 3 4 5 6 7 8 9 mark position limit capacity

NIO (cont.) FileChannel.read(ByteBuffer src, int o, int length); SocketChannel.write(ByteBuffer src); clear() – preparing a buffer for filling flip() – preparing the buffer for draining 1 2 3 4 5 6 7 8 9 position limit capacity 1 2 3 4 5 6 7 8 9 position limit capacity 1 2 3 4 5 6 7 8 9 position limit capacity

NIO (cont.) rewind() – preparing the buffer for another draining compact() – moves the elements between the current position and the limit to the beginning of the buffer direct versus nondirect buffers 1 2 3 4 5 6 7 8 9 position limit capacity 1 2 3 4 5 6 7 8 9 position limit capacity

Selector and SelectionKey Provide a mechanism for multiplexing access to channels. register a channel (along with a set of operations that the selector should watch for) chan.register(readSelector, SelectionKey.OP_READ, new StringBuffer()); OP_ACCEPT OP_CONNECT OP_READ OP_WRITE watching the channels readSelector.selectNow(); select() blocks until at least one channel has activity select(long timeout) as select() with timeout selectNow() returns immediately

Selector (cont.) accessing the channels readSelector.selectedKeys(); returns a Set of SelectionKeys use an Iterator to get the keys key.channel() returns the channel

Example: ChatterBox ChatterServer is a multi-user chat application that allows for any number of users to connect to the server and send text messages to one another. The server needs to perform the following main functions: Accept client connections Read messages from clients Write messages to clients Handle disconnections (graceful or otherwise)

ChatterServer Important attributes: private ServerSocketChannel sSockChan; private Selector readSelector; private LinkedList clients; private ByteBuffer readBuffer; private ByteBuffer writeBuffer; private CharsetDecoder asciiDecoder; private Logger log = Logger.getLogger(ChatterServer.class);

private static final int PORT = 10997; private void initServerSocket() { try { // open a non-blocking server socket channel sSockChan = ServerSocketChannel.open(); sSockChan.configureBlocking(false); // bind to localhost on designated port InetAddress addr = InetAddress.getLocalHost(); sSockChan.socket().bind( new InetSocketAddress(addr, PORT)); // get a selector for multiplexing the client channels readSelector = Selector.open(); } catch (Exception e) { log.error("error initializing server", e);

private void acceptNewConnections() { try { SocketChannel clientChannel; while ((clientChannel = sSockChan.accept()) != null) { addNewClient(clientChannel); log.info("got connection from: " + clientChannel.socket().getInetAddress()); sendBroadcastMessage("login from: " + clientChannel.socket().getInetAddress(), clientChannel); sendMessage(clientChannel, "\n\nWelcome to ChatterBox, there are " + clients.size() + " users online.\n"); sendMessage(clientChannel, "Type 'quit' to exit.\n"); } catch (IOException ioe) { log.warn("error during accept(): ", ioe); catch (Exception e) { log.error("exception in acceptNewConnections()", e);

private void addNewClient(SocketChannel chan) { // add to our list clients.add(chan); // register the channel with the selector // store a new StringBuffer as the Key's attachment for // holding partially read messages try { chan.configureBlocking( false); SelectionKey readKey = chan.register(readSelector, SelectionKey.OP_READ, new StringBuffer()); } catch (ClosedChannelException cce) { catch (IOException ioe) {

private void sendMessage(SocketChannel channel, String mesg) { prepWriteBuffer(mesg); channelWrite(channel, writeBuffer); } private void sendBroadcastMessage(String mesg, SocketChannel from) { Iterator i = clients.iterator(); while (i.hasNext()) { SocketChannel channel = (SocketChannel)i.next(); if (channel != from) channelWrite(channel, writeBuffer); private void prepWriteBuffer(String mesg) { writeBuffer.clear(); writeBuffer.put(mesg.getBytes()); writeBuffer.putChar('\n'); writeBuffer.flip();

private void channelWrite(SocketChannel channel, ByteBuffer writeBuffer) { long nbytes = 0; long toWrite = writeBuffer.remaining(); // loop on the channel.write() call since it will not necessarily // write all bytes in one shot try { while (nbytes != toWrite) { nbytes += channel.write(writeBuffer); Thread.sleep(CHANNEL_WRITE_SLEEP); } catch (InterruptedException e) {} catch (ClosedChannelException cce) { catch (Exception e) { // get ready for another write if needed writeBuffer.rewind();

private void readIncomingMessages() { try { readSelector.selectNow(); Set readyKeys = readSelector.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey key = (SelectionKey) i.next(); i.remove(); SocketChannel channel = (SocketChannel) key.channel(); readBuffer.clear(); long nbytes = channel.read(readBuffer); if (nbytes == -1) { log.info("disconnect: " + channel.socket().getInetAddress() + ", end-of-stream"); channel.close(); clients.remove(channel); sendBroadcastMessage("logout: " + channel.socket().getInetAddress() , channel); }

else { StringBuffer sb = (StringBuffer)key.attachment(); readBuffer.flip( ); String str = asciiDecoder.decode(readBuffer).toString(); readBuffer.clear( ); sb.append( str); String line = sb.toString(); … sendBroadcastMessage(channel.socket().getInetAddress() + ": " + line, channel); }

ChatterClient The ChatterClient needs to perform three tasks: Connect to the server Send messages Receive messages The client uses two threads, one for console input/writing and the main execution thread.

private void connect(String hostname) { try { readSelector = Selector.open(); InetAddress addr = InetAddress.getByName(hostname); channel = SocketChannel.open(new InetSocketAddress(addr, PORT)); channel.configureBlocking(false); channel.register(readSelector, SelectionKey.OP_READ, new StringBuffer()); } catch (UnknownHostException uhe) { catch (ConnectException ce) { catch (Exception e) {