2013-10-14 46 views
0

當我嘗試通過audiotrack播放pcm數據時,我使用jLayer lib解碼了mp3,並給出了很多音頻失真。在audiotrack中播放PCm數據

我的解碼器代碼:

public static void decode(String path, int startMs, int maxMs) 
       throws IOException { 
       ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); 

       float totalMs = 0; 
       boolean seeking = true; 

       File file = new File(path); 
       System.out.println("the data "+path); 
       InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 8 * 1024); 
       try { 
       Bitstream bitstream = new Bitstream(inputStream); 
       Decoder decoder = new Decoder(); 

       boolean done = false; 
       while (! done) { 
        javazoom.jl.decoder.Header frameHeader = bitstream.readFrame(); 
        if (frameHeader == null) { 
        done = true;  
        } else { 
        totalMs += frameHeader.ms_per_frame(); 

        if (totalMs >= startMs) { 
         seeking = false; 
        } 

        if (! seeking) { 
         SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream); 

         if (output.getSampleFrequency() != 44100 
          || output.getChannelCount() != 2) { 
         // throw new com.mindtherobot.libs.mpg.DecoderException("mono or non-44100 MP3 not supported"); 
         } 

         short[] pcm = output.getBuffer(); 
         byte[] bs; 
         int index=0; 
         ByteBuffer buffer; 
         buffer = ByteBuffer.allocate(2*pcm.length); 

         for (short s : pcm) {  
//      outStream.write(s & 0xff);  
//      outStream.write((s >> 8) & 0xff); 


         buffer.putShort(s); 



         }  

         byte[] dataaudio = buffer.array(); 

         //return buffer.array(); 






         track.write(dataaudio, 0, dataaudio.length); 

        } 

        if (totalMs >= (startMs + maxMs)) { 
         done = true; 
        } 
        } 
        bitstream.closeFrame(); 
       } 

       //return outStream.toByteArray(); 
       } catch (BitstreamException e) { 
       throw new IOException("Bitstream error: " + e); 
       } catch (DecoderException e) { 
       Log.w("data", "Decoder error", e); 
       ; 
       } finally { 
       // IOUtils.safeClose(inputStream);  
       } 
      } 
+0

爲什麼不使用MediaPlayer?它會自動解碼您的音頻文件併爲您播放。 – tiguchi

+0

感謝您的回覆,實際上我想將數據傳輸到其他設備... – user2705259

+0

我明白了...也許您應該給一個原生MP3解碼庫一個嘗試。它將比用Java編寫的解碼器更快,也許你也會擺脫音頻失真問題。 – tiguchi

回答

0

我建議你不要將您的短[]爲byte [],但寫你的短[]將AudioTrack即致電track.write(PCM ,0,pcm.length)而不是track.write(dataaudio,0,dataaudio.length)。

我一直在爲Android編寫一個音頻處理器,它使用JLayer來讀取MP3文件,處理數據,然後輸出到AudioTrack。如果我不做任何數據處理,但只是將數據從JLayer發送到AudioTrack,它在我的Nexus7上播放效果非常好。 然而,當我做我的處理(變調和/或時間壓縮),我得到一個惱人的裂紋。當我從JLayer讀取一幀並將其發送到AudioTrack(沒有處理)時,聽起來不錯,但是當我從JLayer讀取兩幀並將它們發送到AudioTrack(不處理)時,我就聽到了這個crack啪聲!

我已經開始在Android之外進行一些調查了(基本上運行相同的代碼,但是用我自己的AudioTrack虛擬實現,它可以在我的筆記本電腦上播放聲音或轉換爲WAV文件)&迄今爲止的結果非常奇。

所以,如果你有進一步的發展,我很想知道你在做什麼。

相關問題