2017-03-17 41 views
-1

我想用一個.mp3音頻流來繪製一個波形,用大膽使用的最小/最大算法。該算法從樣本的「塊」中計算最小值和最大值,並在兩點之間繪製垂直線。我可以用這種方式幾乎正確地繪製波形,但有一些錯誤。這裏是一個圖像: waveform如何正確繪製具有最小/最大算法的波形? (就像大膽的一樣)

正如你可以看到,在一開始的波形被正確地繪製本身,但隨後「空白」開始出現,就像如果我是避免畫一些線條。我找不到我的代碼中的錯誤,並找到幫助!這裏是代碼:

/** 
* 
* */ 
private void createWaveform(){ 

    //Array that will contain all the chunks from the audio 
    Array<float[]> chunks = new Array<float[]>(); 
    //the length of the audio in samples 
    int length = audio.getLengthInSamples(); 
    //the amount of samples per pixel. w = screen width 
    samplesPerPixel = length/(int)w; 
    //get all samples 
    float[] samples = audio.getSamples(); 
    //this is strange, but divides the samples in chunks. i can't find other way, better options are welcome 
    int max = samplesPerPixel; 
    int n = 0; 

    for (int i = 0; i < w; i++){  
     float[] chunk = new float[samplesPerPixel]; 
     int k = 0; 
     for (int j = n ; j < max; j++){ 
      chunk[k] = samples[j]; 
      k++; 
     } 
     chunks.add(chunk); 
     n = max; 
     max+=samplesPerPixel; 
    } 

    min_max(chunks); 

} 

/** 
* perform the min/max algorithm of all chunks and creates the lines between points 
* */ 
public void min_max(Array<float[]> chunks){ 
    float max, min; 
    float x = this.getX(); 
    float y = this.getY()+this.h/2; 

    for (int i = 0; i < chunks.size; i++){ 

     max = getMax(chunks.get(i))*(h/2); 
     min = getMin(chunks.get(i))*(h/2); 

     Line l = new Line(new Point(x+i,y+max), new Point(x+i,y+min)); 
     lines.add(l); 
    } 

} 

/** 
* 
* */ 
private void drawLines(ShapeRenderer shapeRenderer){ 

    for (int i = 0 ; i <lines.size; i++) { 
     Line l = lines.get(i); 
     Point p1 = l.getPMin(); 
     Point p2 = l.getPMax(); 
     try { 
      shapeRenderer.line(p1.x, p1.y, p2.x, p2.y); 
     }catch(Exception e){ 
      System.out.println("error"); 
     } 
    } 

} 
+0

我正在使用java和libgdx –

回答

1

如果有人試圖用java在libgdx中實現相同的算法,我發現了一個解決方案。不要使用ShapeRenderer,而應使用Pixmaps和bug消失。如果你只使用java,不用擔心,第一篇文章中的算法工作正常,你只需要適應一些東西,因爲你可能使用的是swing或其他圖形庫,但邏輯是相同的。最終結果:waveformFixed

相關問題