2014-01-06 48 views
0

當我運行下面的代碼時,我沒有聲音作爲輸出,而是它給了我噪音。獲取噪聲作爲輸出而不是混合聲音

我在我的資源文件夾中有兩個音頻文件,並使用1個inputstream將這些文件轉換爲bytearray.If我添加mp3,然後應用程序不幸關閉。

private void mixSound() throws IOException { 
AudioTrack audioTrack =new AudioTrack(AudioManager.STREAM_MUSIC,44100,AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100, AudioTrack.MODE_STREAM); 
     Log.i(tag,"inside mixSound"); 
     InputStream in1=getResources().openRawResource(R.raw.cut1);  s 
     InputStream in2=getResources().openRawResource(R.raw.cut2); 

     byte[] music1 = null; 
     music1= new byte[in1.available()]; 
     Log.i(tag,"in1"); 
     music1=convertStreamToByteArray(in1); 
     in1.close(); 


     byte[] music2 = null; 
     music2= new byte[in2.available()]; 
     music2=convertStreamToByteArray(in2); 
     in2.close(); 
     byte[] output = new byte[music1.length]; 

     audioTrack.play(); 

     for(int i=0; i < output.length; i++){ 

      float samplef1 = music1[i]/128.0f;  //  2^7=128 
      float samplef2 = music2[i]/128.0f; 


      float mixed = samplef1 + samplef2; 
      // reduce the volume a bit: 
      mixed *= 0.8; 
      // hard clipping 
      if (mixed > 1.0f) mixed = 1.0f; 

      if (mixed < -1.0f) mixed = -1.0f; 

      byte outputSample = (byte)(mixed * 128.0f); 
      output[i] = outputSample; 

     } //for loop 
     audioTrack.write(output, 0, output.length); 

    } 

     public static byte[] convertStreamToByteArray(InputStream is) throws IOException { 



      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      byte[] buff = new byte[10240]; 
      int i = Integer.MAX_VALUE; 
      Log.i(tag,"in csb"); 
      while ((i = is.read(buff, 0, buff.length)) > 0) { 
       baos.write(buff, 0, i); 
      } 

      return baos.toByteArray(); 
     } 

感謝您提前的幫助。

+0

你的音頻文件格式是? – Michael

+0

我爲此使用了wav格式的文件。但它仍然不起作用。 – ank

+0

我的意思是比這更具體。該文件是否包含任何標題數據?音頻壓縮或原始PCM?每個採樣是否使用8位或16位? – Michael

回答

0

這裏有幾個問題...

  1. 如果您正在使用16位PCM音頻(由你的AudioTrack初始化看來你是)工作,那麼你應該訪問您的源音頻和寫到AudioTrackshort s(它們是16位),而不是byte s(8位)。如果你必須閱讀從源byte S,你需要在你的循環中的時間閱讀了其中兩個,這樣做

    short curSample = (myByteArr[i] << 8) | myByteArr[i+1]; 
    

    ,然後將結果寫入您的存儲緩衝器。這假設你有16位短褲存儲在你正在閱讀的文件中,你應該這樣做。儘管如此,儘管只是把它們看作是他們自己的東西。

  2. 使用AudioTrack.MODE_STREAM意味着當音頻播放時,您將連續寫入緩衝區。你在這裏完成的方式填充整個緩衝區,然後寫入到AudioTrack。如果這是一次性播放,則應該使用AudioTrack.MODE_STATIC

  3. 這是一個角落的情況,但考慮如果mixed == 1.0f會發生什麼情況。如果將其乘以128.0f並截斷爲byte,則會得到128,這實際上超出了簽名byte的範圍(因爲爲0,範圍爲[-128,127])。

我認爲問題1是噪音的來源。您需要保持您的16位PCM數據完好無損,而不是將其分開。