2012-02-15 15 views
1

JLayer/BasicPlayerライブラリを使用してHTTP経由でリモートMP3ファイルを再生するアプリケーションがあります。再生したmp3ファイルを再ダウンロードせずにディスクに保存したい。Javaで再生中にmp3ファイルをディスクに書き込む

これは、JLayerベースのBasicPlayerを使用してMP3ファイルを再生するコードです。

String mp3Url = "http://ia600402.us.archive.org/6/items/Stockfinster.-DeadLinesutemos025/01_Push_Push.mp3"; 
URL url = new URL(mp3Url); 
URLConnection conn = url.openConnection(); 
InputStream is = conn.getInputStream(); 
BufferedInputStream bis = new BufferedInputStream(is); 

BasicPlayer player = new BasicPlayer(); 
player.open(bis); 
player.play(); 

どのようにしてmp3ファイルをディスクに保存できますか?

答えて

3

バイトを2回通過しないようにするには、接続からの入力ストリームを、出力ストリームに読み込まれたデータ、つまり一種の「ティーパイプ入力ストリーム」を書き込むフィルタでラップする必要があります。 "そのようなクラスはあなた自身を書くのは難しいことではありませんが、Apache Commons IOライブラリのTeeInputStreamを使って作業を保存することができます。

のApache CommonsのIO:http://commons.apache.org/io/
TeeInputStreamのJavaDoc:http://commons.apache.org/io/apidocs/org/apache/commons/io/input/TeeInputStream.html

編集:概念実証:それを使用する方法

import java.io.*; 

public class TeeInputStream extends InputStream { 
    private InputStream in; 
    private OutputStream out; 

    public TeeInputStream(InputStream in, OutputStream branch) { 
     this.in=in; 
     this.out=branch; 
    } 
    public int read() throws IOException { 
     int read = in.read(); 
     if (read != -1) out.write(read); 
     return read; 
    } 
    public void close() throws IOException { 
     in.close(); 
     out.close(); 
    } 
} 

... 
BufferedInputStream bis = new BufferedInputStream(is); 
TeeInputStream tis = new TeeInputStream(bis,new FileOutputStream("test.mp3")); 

BasicPlayer player = new BasicPlayer(); 
player.open(tis); 
player.play(); 
+0

を使用し、完全に正常に動作します - あなたに感謝! – nanoman

0
BufferedInputStream in = new BufferedInputStream(is); 

OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePathAndFilename))); 
    byte[] buf = new byte[256]; 
    int n = 0; 
    while ((n=in.read(buf))>=0) { 
     out.write(buf, 0, n); 
    } 
    out.flush(); 
    out.close(); 
0

最初にストリームをディスクに書き込むには、FileInputStreamを使用します。その後、ファイルからストリームをリロードします。

0

ラップします独自のInputStream

class myInputStream extends InputStream { 

    private InputStream is; 
    private FileOutputStream resFile; 
    public myInputStream(InputStream is) throws FileNotFoundException { 
     this.is = is; 
     resFile = new FileOutputStream("path_to_result_file"); 
    } 

    @Override 
    public int read() throws IOException { 
     int b = is.read(); 
     if (b != -1) 
      resFile.write(b); 
     return b; 
    } 

    @Override 
    public void close() { 
     try { 
      resFile.close(); 
     } catch (IOException ex) { 
     } 
     try { 
      is.close(); 
     } catch (IOException ex) { 
     } 
    } 
} 

とストレートポイントに

InputStream is = conn.getInputStream(); 
myInputStream myIs = new myInputStream(is); 
BufferedInputStream bis = new BufferedInputStream(myIs); 
関連する問題