2012-02-15 115 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

爲了避免必須遍歷字節兩次,您需要將來自連接的輸入流包裝在一個過濾器中,該過濾器將讀取到的任何數據寫入輸出流,即一種「三通管道輸入流」。 「這樣的類並不難編寫,但您可以使用Apache Commons IO庫中的TeeInputStream來保存工作。

阿帕奇百科全書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 2012-02-16 07:44:29

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);