我真的很困惑,爲什麼當我使用下面顯示的代碼時,我得到一個0kb文件。作爲Java網站關於這個類的說明,我應該工作。但是...我想要生成一個正弦波並輸出其結果到一個txt填充雙。這是我的代碼的第一步,我陷入了這樣一個簡單的問題。也許我不太瞭解如何使用類文件和數據流,就像我從官方網站上學到的那樣。爲什麼我在使用datainputstream,java,android時會得到一個0kb文件?
public class audioplayThread implements Runnable {
private File file;
private FileOutputStream ops;
private BufferedOutputStream bos;
private DataOutputStream dos;
private double Omega;
private int f = 18*1000;
private double pi;
private int samplenumber = 84; //Assume OFDM symbol has 64 real value and
private static final int Encording = AudioFormat.ENCODING_PCM_16BIT; //Data size for each frame = 16 bytes
private static final int Sample_rate = 48000; //Sample rate = 48000 HZ
private static final int Channel = AudioFormat.CHANNEL_OUT_MONO; //Set as single track
private static final int Buffersize = AudioTrack.getMinBufferSize(Sample_rate, Channel,Encording);
@Override
public void run() {
// TODO Auto-generated method stub
file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(),"mmm.txt");
if(file.exists()){
file.delete();
}
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
/*Create a datastream*/
ops = new FileOutputStream(file);
bos = new BufferedOutputStream(ops);
dos = new DataOutputStream(bos);
/*Set sine wave parameter*/
pi = Math.PI;
Omega = 2*pi*f/Sample_rate;
/*Build instance for audiotrack*/
//AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,Sample_rate, Channel, Encording, Buffersize, AudioTrack.MODE_STREAM);
/*build sine wave*/
double[] buffer = new double[samplenumber];
for(int i=0;i<samplenumber;i++){
buffer[i] = Math.sin(Omega*i);
dos.writeDouble(buffer[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
您是否試過關閉流?你正在緩衝,從不關閉它們,數據可能會丟失v –
呃......我很愚蠢,我怎麼能忘記關閉它。謝謝!還有一個問題,爲什麼我在txt文件中獲取這些數據是不可讀的代碼? – MarvinC
因爲您使用的是使用二進制格式的'DataOutputStream'。 –