Java Stream Audio

ts230

Gesperrt
Hallo!
Ich habe eine Frage.
Ich möchte einen kleinen Audio Streaming Server machen. Der soll Audio das von einem Mikrofon aufgenomenen Audo Streamen. Also wenn man z.b. die URL "localhost:4444/stream" aufruft,kann mann halt Alles am Mikrofon hören--und zwar life.
Und das audio Format sollte möglichst von Linux,Windows und mac abspielbar sein.
 
Moin,

Joah, schön.
Aber ... wo ist Deine Frage?
Was ist der Sinn Deines Beitrags?

Klär uns doch bitte auf :)

Gruß,
Xan
 
Ich möchte einfach Audio vom Mikrofon auf einem kleinen Server streamen. Sozusagen wie Internet Radio.
 
Was dir vorschwebt, wissen wir mittlerweile schon.

Vielmehr wollte Xandro in Erfahrung bringen, wo sich nun konkret Hürden in den Weg stellen.

mfg Maik
 
Oh,sorry.
Also es hapert am Streamen. Ich kann schon in eine Datei aufnehmen,aber auf einen Stream spinnts.
 
Moin,

Deine Ausführungen sind ziemlich spärlich.
Gib uns doch mal was handfestes, am Besten wäre natürlich Code.
Es gibt die Klasse AudioInputStream, vielleicht schaust Du Dir diese mal an.
Ansonsten würde ich das alles wohl über ein ByteArray-Stream-Konzept lösen.
Aber das ist nur mein Vorschlag.

Gruß,
Xan
 
So nehme ich in eine Datei auf:
Java:
public class Recorder extends Thread{
String file=null;
  TargetDataLine targetDataLine;

public Recorder(String FileN){file=FileN;    stopped=false;}


        @Override
public void run(){
            setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread arg0, Throwable arg1) {
                     new Bug$Reporter$Dialog(Piano.this, true, arg1);
                }});
                File audioFile = null;
            try {
                    stopped=false;
                AudioFileFormat.Type fileType = null;
                //No:AU,AIFC,SND
                //OK:WAVE,AIFF
                fileType = formats[jComboBox4.getSelectedIndex()];
                
                audioFile = new File(file);
                DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, null);
                targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
                targetDataLine.open(targetDataLine.getFormat());
                targetDataLine.start();
     AudioSystem.write(new AudioInputStream(targetDataLine), fileType, audioFile);
    
     jLabel1.setText(Float.toString(targetDataLine.getLevel()));
 } catch (IOException ex) {
                Logger.getLogger(Piano.class.getName()).log(Level.SEVERE, null, ex);
                new Bug$Reporter$Dialog(Piano.this, true, ex);
            } catch (LineUnavailableException ex) {
                Logger.getLogger(Piano.class.getName()).log(Level.SEVERE, null, ex);
                new Bug$Reporter$Dialog(Piano.this, true, ex);
            }
byte[] a = new byte[8];                
                    while(!stopped){
                     String aA = String.format("%.2f", targetDataLine.getLevel()); 
                     Float y =Float.parseFloat(aA);                          
                     int m=0;
                     m =Math.round(y * 100);
                     if(m > 0){
                     jProgressBar2.setValue(m);
                     jProgressBar3.setValue(m);
                     }
                     jLabel1.setText(Float.toString(targetDataLine.getLevel()));
   }
          
   if(stopped){targetDataLine.drain();
   targetDataLine.close();
   jLabel1.setText("done recording");
               }    
          

  }
    }
Es nimmt auf in einem seperaten Thread bis das Boolean flag "stopped" auf true gesetzt wird. Es gibt außerdem das Problem das dass getLevel() immer -1.0 ist und ich habe es schon auf 5 verschiedenen Computern getestet(Linux,Windows,Mac).
Dann habe ich einen kleinen HTTP Server gebastelt:
Java:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package onscreenpiano;


import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
//ava.util.prefs.Base64
import javax.sound.sampled.*;


/**
 *
 * @author tristan
 */
//file: server.java
//the real (http) serverclass
//it extends thread so the server is run in a different
//thread than the gui, that is to make it responsive.
//it's really just a macho coding thing.
public class HTTPServer extends Thread {
public String AddHeader;
public String sysString = null;
public Boolean secure=false;
public Boolean continueReq=true;
public String passw,userN,Base64Str="";
public String Strings[] = new String[10];
    private boolean unknown = false;
    private boolean stopped;
public void AddSecure(String user,String Password,String relam){
//AddHeader="WWW-Authenticate: Basic realm=\""+relam+"\"";    
passw=Password;
userN=user;
String tmp=user+":"+passw;
Base64Str=Base64.base64Encode(tmp);
tmp=null;
//secure=true;
continueReq=true;
}
//the constructor method
//the parameters it takes is what port to bind to, the default tcp port
//for a httpserver is port 80. the other parameter is a reference to
//the gui, this is to pass messages to our nice interface
  public HTTPServer(int listen_port/*,Sett sA*/) {
        port = listen_port;
    //    s=sA;

//this makes a new thread, as mentioned before,it's to keep gui in
//one thread, server in another. You may argue that this is totally
//unnecessary, but we are gonna have this on the web so it needs to
//be a bit macho! Another thing is that real pro webservers handles
//each request in a new thread. This server dosen't, it handles each
//request one after another in the same thread. This can be a good
//assignment!! To redo this code so that each request to the server
//is handled in its own thread. The way it is now it blocks while
//one client access the server, ex if it transferres a big file the
//client have to wait real long before it gets any response.
    this.start();
    InetAddress localaddr=null;
        try {
            localaddr = InetAddress.getLocalHost();
        } catch (UnknownHostException ex) {
            Logger.getLogger(HTTPServer.class.getName()).log(Level.SEVERE, null, ex);
        }

    String t1=null;
    String t2=null;
    String t3=null;
    String t4=null;
    t1=System.getProperty("os.name");
    t2=System.getProperty("os.arch");
    t3=System.getProperty("user.language");
    sysString=t1+" "+t2+" (Language "+t3+" JRE Version "+System.getProperty("java.runtime.version")+")Server at "+localaddr.getHostAddress()+" Port "+Integer.toString(port)+" Hostname="+localaddr.getHostName()+"";
  }

    private String getFileType(File f) {
        String img = "http://tiersendung.ti.funpic.de/icons/unknown.gif";
        if(unknown == false)img = "http://tiersendung.ti.funpic.de/icons/bomb.png";
        
if(f.getName().toUpperCase().contains("README") == true){img = "http://tiersendung.ti.funpic.de/icons/hand.right.gif";}
else if(f.getName().toLowerCase().endsWith(".gz") == true || f.getName().toLowerCase().endsWith(".ar") == true || f.getName().toLowerCase().endsWith(".zip") == true){img = "http://tiersendung.ti.funpic.de/icons/compressed.png";}
else if(f.getName().toLowerCase().endsWith(".html") == true || f.getName().toLowerCase().endsWith(".htm") == true){img = "http://tiersendung.ti.funpic.de/icons/layout.png";}
else if(f.getName().toLowerCase().endsWith(".png") == true || f.getName().toLowerCase().endsWith(".gif") == true || f.getName().toLowerCase().endsWith(".jpg") == true){img = "http://tiersendung.ti.funpic.de/icons/image2.png";}
else if(f.getName().toLowerCase().endsWith(".bin") == true){img = "http://tiersendung.ti.funpic.de/icons/binary.png";}
else if(f.getName().toLowerCase().endsWith(".pdf") == true){img = "http://tiersendung.ti.funpic.de/icons/pdf.png";}
else if(f.getName().toLowerCase().endsWith(".txt") == true || f.getName().toLowerCase().endsWith(".text") == true){img = "http://tiersendung.ti.funpic.de/icons/text.png";}
return img;
    }

  private void s(String s2) { //an alias to avoid typing so much!
System.out.print(s2);
  }


  private int port; //port we are going to listen to

//this is a overridden method from the Thread class we extended from
  @Override
  public void run() {
    //we are now inside our own thread separated from the gui.
    ServerSocket serversocket = null;
    //Pay attention, this is where things starts to cook!
    try {
      //print/send message to the guiwindow
      //make a ServerSocket and bind it to given port,
      serversocket = new ServerSocket(port);
    }
    catch (Exception e) { //catch any errors and print errors to gui
      return;
    }
    //go in a infinite loop, wait for connections, process request, send response
    while (true) {
            try {
                Socket ConnSock = serversocket.accept();
                new HTTPThread(ConnSock).start();
            } catch (IOException ex) {
                Logger.getLogger(HTTPServer.class.getName()).log(Level.SEVERE, null, ex);
            }

    } //go back in loop, wait for next request
  }

public class HTTPThread extends Thread{
Socket s;
public HTTPThread(Socket soc){s=soc;}
public void run(){
      try {
        //figure out what ipaddress the client commes from, just for show!
        InetAddress client = s.getInetAddress();
        //and print it to gui
        s(client.getHostName() + " connected to server.\n");
        //Read the http request from the client from the socket interface
        //into a buffer.
        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
        //Prepare a outputstream from us to the client,
        //this will be used sending back our response
        //(header + requested file) to the client.
        DataOutputStream output = new DataOutputStream(s.getOutputStream());

//as the name suggest this method handles the http request, see further down.
//abstraction rules
        http_handler(input, output);
      }
      catch (Exception e) { //catch any errors, and print them
        s("\nError:" + e.getMessage());
      }
}
}

//our implementation of the hypertext transfer protocol
//its very basic and stripped down
  private void http_handler(BufferedReader input, DataOutputStream output) {
    int method = 0; //1 get, 2 head, 0 not supported
    String http = new String(); //a bunch of strings to hold
    String path = new String(); //the various things, what http v, what path,
    String file = new String(); //what file
    String user_agent = new String(); //what user_agent
    String[] POST;
    String res;
    String stat;
    String inf;
    String rest;
    String tmpp = new String();
    String[] T;
    try {
      //This is the two types of request we can handle
      //GET /index.html HTTP/1.0
      //HEAD /index.html HTTP/1.0
      String tmp = input.readLine(); //read from the stream
      String y;
      /*
      while((y = input.readLine()) !="Content-Length:"){}
      if((y = input.readLine()) == "Content-Length:"){
      y=input.readLine();
      if(y == "\r\n"){y=input.readLine();}
      else{tmpp = y;}
      T = tmpp.split("&");
    //  int yA=0;
      for(int aa = 0;aa == T.length;aa++){
   //   POST[yA] = T[aa].split("=");
 //     yA++;
          if(T[aa].toLowerCase() == "res"){res = T[aa+1];}
          else if(T[aa].toLowerCase() == "stat"){stat = T[aa+1];}
          else if(T[aa].toLowerCase() == "inf"){inf = T[aa+1];}
          else if(T[aa].toLowerCase() == "rest"){rest = T[aa+1];}
          else{}
     //  aa = aa+1;   
      }
      }*/
          
          Strings[0]=tmp;
      for(int i = 1;i == 10;i++){
      Strings[i]=input.readLine();    
      }
              //Au
continueReq=true;
      String tmp2 = new String(tmp);
      tmp.toUpperCase(); //convert it to uppercase
      if (tmp.startsWith("GET")) { //compare it is it GET
        method = 1;
      } //if we set it to method 1
      if (tmp.startsWith("HEAD")) { //same here is it HEAD
        method = 2;
      } //set method to 2

      if (method == 0) { // not supported
        try {
          output.writeBytes(construct_http_header(501, 0));
          output.close();
          return;
        }
        catch (Exception e3) { //if some error happened catch it
          s("error:" + e3.getMessage());
        } //and display error
      }
      //}

      //tmp contains "GET /index.html HTTP/1.0 ......."
      //find first space
      //find next space
      //copy whats between minus slash, then you get "index.html"
      //it's a bit of dirty code, but bear with me...
      int start = 0;
      int end = 0;
      for (int a = 0; a < tmp2.length(); a++) {
        if (tmp2.charAt(a) == ' ' && start != 0) {
          end = a;
          break;
        }
        if (tmp2.charAt(a) == ' ' && start == 0) {
          start = a;
        }
      }
      path = tmp2.substring(start + 2, end); //fill in the path
    }
    catch (Exception e) {
      s("errorr" + e.getMessage());
    } //catch any exception
//Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
/*
    for(int i=0;i == 10;i++){
//Strings[i];
String y = new String(Strings[i]);
if (y.indexOf("Authorization: Basic") != -1){
//ding-ding-ding!
int va = y.indexOf("ion: Basic ");
va = va +11;
String code = y.substring(va);
if(code == Base64Str){continueReq=true;}
else{continueReq=false;}
//Something authenticated our response
 */
//}
//}        
    //path do now have the filename to what to the file it wants to open
       FileInputStream requestedfile = null;

    try {
      //NOTE that there are several security consideration when passing
      //the untrusted string "path" to FileInputStream.
      //You can access all files the current user has read access to
      //current user is the user running the javaprogram.
      //you can do this by passing "../" in the url or specify absoulute path
      //or change drive (win)

      //try to open the file,
     if(new File(path).isDirectory() == false)requestedfile = new FileInputStream(path);
    }
    catch (Exception e) {
      try {
        //if you could not open the file send a 404
       // output.writeBytes(construct_http_header(404, 0));
          output.writeBytes(construct_http_header(404,7));
          output.writeBytes("<html><body background-color=white><pre><img src='http://tbn2.google.com/images?q=tbn:5hyiGvNhbKDaxM:http://images4.wikia.nocookie.net/naruto/images/thumb/6/64/Icon-Warning-Yellow.svg/600px-Icon-Warning-Yellow.svg.png' style='float:left;width:113px;'><h2>Sorry,the file does not exist!</h2><br />The file &quot;"+path+"&quot does not exist.If you think this is wrong,please contect the website-owner.<br />Exception-Message:<font color=red>"+e.getMessage()+"</font><br />Exception-type:<font color=red>"+e.getClass().toString()+"</font><br /><small>JAVAHTTPSERVER v 0.1&nbsp;"+sysString+"</small></pre></html></body>");
          
        //close the stream
        output.close();
      }
      catch (Exception e2) {}

      s("error" + e.getMessage());
    } //print error to gui
    //happy day scenario
    try {
      int type_is = 0;
      //find out what the filename ends with,
      //so you can construct a the right content type
      if (path.endsWith(".zip") || path.endsWith(".exe")
           ) {
        type_is = 3;
      }
      if( path.endsWith(".tar")){type_is = 5;}
      if(path.endsWith(".tar.gz")){type_is = 6;}
      if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
        type_is = 1;
      }
       if (path.endsWith(".txt") || path.endsWith(".text")) {
        type_is = 4;
      }
      if (path.endsWith(".gif")) {
        type_is = 2;
        //write out the header, 200 ->everything is ok we are all happy.
      }
  //    if(tmp)
      continueReq=true;
File dir = new File(path);
String AAA ="/";
String[] ya;
ya = path.split("/");
for(int g = 0;g < ya.length -1;g++){
AAA+=ya[g]+"/";    
}

String list="<html><title>Directory listing</title><body background-color=white><h2><pre>Directory listing of &quot;"+path+"&quot;</pre></h2><table><tr><td><pre>Name</pre></td><td><pre>Size</pre></td><td><pre>Last modified</pre></td></tr>";
list+="<tr><td><pre><a href='"+AAA+"'><img src='http://tiersendung.ti.funpic.de/icons/back.gif' border=0>Parent directory</a></pre></td></tr>";

if(dir.isDirectory()){
String[] files = dir.list();
long size;
String SS;
for(int i = 0;i < files.length;i++){
File f=new File(path+"/"+files[i]);
if(f.length() > 1023){SS = Double.toString(f.length()/1024)+"&nbsp;KByte";}
else{SS = Long.toString(f.length())+"&nbsp;Byte";}
String DoSl="";
  Long lastModified = f.lastModified();
  Date lastMod = new Date(lastModified);
String img = null;
if(f.isDirectory() == true){DoSl="/";img ="http://tiersendung.ti.funpic.de/icons/folder.gif";}
else if(f.isDirectory() == false){DoSl="/";img=getFileType(f);}
list = list + "\n\r<tr><td><pre><a href='/"+path+""+DoSl+""+files[i]+"'><img src='"+img+"' border=0>"+files[i]+"</a></pre></td><td><pre>"+SS+"</pre></td><td><pre>&nbsp;&nbsp;"+lastMod.toString()+"</pre></td></tr>"; 
}
list=list+"\n\r</table><br /><small>JAVAHTTPSERVER v0.1&nbsp;"+sysString+"</small></body></html>";

}
if(dir.isDirectory() == false)output.writeBytes(construct_http_header(200, type_is));
      

      //if it was a HEAD request, we don't print any BODY
      if (method == 1) { //1 is GET 2 is head and skips the body
        while (true) {
          //read the file from filestream, and print out through the
          //client-outputstream on a byte per byte base.
if(dir.isDirectory() == false){
          int b = requestedfile.read();
               if (b == -1) {
            break; //end of file
          }
          if(continueReq == true)output.write(b);
          else {output.writeBytes(construct_http_header(200,7));
          output.writeBytes("<html><body><pre><h2>Sorry,the file is not existing.</h2><br />The file &quot;"+path+"&quot does not exist.If you think this is wrong,please contect the website-owner.<br /><small>JAVAHTTPSERVER v 0.1&nbsp;"+sysString+"</small></pre></html></body>");
          }
          
        }else{
output.writeBytes(construct_http_header(200,7));
output.writeBytes(list);
break;
}}
        
      }
//clean up the files, close open handles
      output.close();
      requestedfile.close();
    }

    catch (Exception e) {}

  }

  //this method makes the HTTP header for the response
  //the headers job is to tell the browser the result of the request
  //among if it was successful or not.
  private String construct_http_header(int return_code, int file_type) {
    String s = "HTTP/1.0 ";

    //you probably have seen these if you have been surfing the web a while
    switch (return_code) {
      case 200:
        s = s + "200 OK";
        break;
      case 400:
        s = s + "400 Bad Request";
        break;
      case 403:
        s = s + "403 Forbidden";
        break;
      case 404:
        s = s + "404 Not Found";
        break;
      case 500:
        s = s + "500 Internal Server Error";
        break;
      case 501:
        s = s + "501 Not Implemented";
        break;
    }

    s = s + "\r\n"; //other header fields,
    s = s + "Connection: close\r\n"; //we can't handle persistent connections
    s = s + "Server: JAVAHTTPServer "+sysString+" V0.1\r\n"; //server name
   if(secure == true){s = s +AddHeader+"\r\n";}

    //Construct the right Content-Type for the header.
    switch (file_type) {
      //plenty of types for you to fill in
      case 0:
      break;
      case 1:
      s = s + "Content-Type: image/jpeg\r\n";
      break;
      case 2:
      s = s + "Content-Type: image/gif\r\n";
      case 3:
      s = s + "Content-Type: application/x-zip-compressed\r\n";
      break;
      case 4:
      s = s + "Content-Type: text/plain\r\n";   
      break;
      case 5:
      s = s + "Content-Type: application/x-tar\r\n";   
      break;
      case 6:
      s = s + "Content-Type: application/x-compressed-tar\r\n";     
      break;
      case 7:
      s = s + "Content-Type: text/html\r\n";
      break;
      default:
      s = s + "Content-Type: text/html\r\n";
     break;
    }

    s = s + "\r\n"; //this marks the end of the httpheader
    return s;
  }

  public static void main(String[] args){new HTTPServer(4444);}
  
}
Dann sollte man z.b. einfach die URL "localhost:4444/stream.htm" aufrufen und dort erscheint eine kleine Webpage in der der Player eingebaut ist(wie z.b. hier).
 
Zuletzt bearbeitet von einem Moderator:

Neue Beiträge

Zurück