显示音频波形

时间:2016-08-03 13:07:24

标签: android audio waveform

我在android中制作了一个音乐应用程序。这个音乐列表来自服务器端。我不知道如何在android中显示音频波形?比如在soundcloud网站上。我在下面附上了图片。enter image description here

2 个答案:

答案 0 :(得分:20)

也许,您可以在没有库的情况下实现此功能,当然,如果您只想要音频样本的可视化。 例如:

public class PlayerVisualizerView extends View {

    /**
     * constant value for Height of the bar
     */
    public static final int VISUALIZER_HEIGHT = 28;

    /**
     * bytes array converted from file.
     */
    private byte[] bytes;

    /**
     * Percentage of audio sample scale
     * Should updated dynamically while audioPlayer is played
     */
    private float denseness;

    /**
     * Canvas painting for sample scale, filling played part of audio sample
     */
    private Paint playedStatePainting = new Paint();
    /**
     * Canvas painting for sample scale, filling not played part of audio sample
     */
    private Paint notPlayedStatePainting = new Paint();

    private int width;
    private int height;

    public PlayerVisualizerView(Context context) {
        super(context);
        init();
    }

    public PlayerVisualizerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        bytes = null;

        playedStatePainting.setStrokeWidth(1f);
        playedStatePainting.setAntiAlias(true);
        playedStatePainting.setColor(ContextCompat.getColor(getContext(), R.color.gray));
        notPlayedStatePainting.setStrokeWidth(1f);
        notPlayedStatePainting.setAntiAlias(true);
        notPlayedStatePainting.setColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
    }

    /**
     * update and redraw Visualizer view
     */
    public void updateVisualizer(byte[] bytes) {
        this.bytes = bytes;
        invalidate();
    }

    /**
     * Update player percent. 0 - file not played, 1 - full played
     *
     * @param percent
     */
    public void updatePlayerPercent(float percent) {
        denseness = (int) Math.ceil(width * percent);
        if (denseness < 0) {
            denseness = 0;
        } else if (denseness > width) {
            denseness = width;
        }
        invalidate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (bytes == null || width == 0) {
            return;
        }
        float totalBarsCount = width / dp(3);
        if (totalBarsCount <= 0.1f) {
            return;
        }
        byte value;
        int samplesCount = (bytes.length * 8 / 5);
        float samplesPerBar = samplesCount / totalBarsCount;
        float barCounter = 0;
        int nextBarNum = 0;

        int y = (height - dp(VISUALIZER_HEIGHT)) / 2;
        int barNum = 0;
        int lastBarNum;
        int drawBarCount;

        for (int a = 0; a < samplesCount; a++) {
            if (a != nextBarNum) {
                continue;
            }
            drawBarCount = 0;
            lastBarNum = nextBarNum;
            while (lastBarNum == nextBarNum) {
                barCounter += samplesPerBar;
                nextBarNum = (int) barCounter;
                drawBarCount++;
            }

            int bitPointer = a * 5;
            int byteNum = bitPointer / Byte.SIZE;
            int byteBitOffset = bitPointer - byteNum * Byte.SIZE;
            int currentByteCount = Byte.SIZE - byteBitOffset;
            int nextByteRest = 5 - currentByteCount;
            value = (byte) ((bytes[byteNum] >> byteBitOffset) & ((2 << (Math.min(5, currentByteCount) - 1)) - 1));
            if (nextByteRest > 0) {
                value <<= nextByteRest;
                value |= bytes[byteNum + 1] & ((2 << (nextByteRest - 1)) - 1);
            }

            for (int b = 0; b < drawBarCount; b++) {
                int x = barNum * dp(3);
                float left = x;
                float top = y + dp(VISUALIZER_HEIGHT - Math.max(1, VISUALIZER_HEIGHT * value / 31.0f));
                float right = x + dp(2);
                float bottom = y + dp(VISUALIZER_HEIGHT);
                if (x < denseness && x + dp(2) < denseness) {
                    canvas.drawRect(left, top, right, bottom, notPlayedStatePainting);
                } else {
                    canvas.drawRect(left, top, right, bottom, playedStatePainting);
                    if (x < denseness) {
                        canvas.drawRect(left, top, right, bottom, notPlayedStatePainting);
                    }
                }
                barNum++;
            }
        }
    }

    public int dp(float value) {
        if (value == 0) {
            return 0;
        }
        return (int) Math.ceil(getContext().getResources().getDisplayMetrics().density * value);
    }
}

很抱歉,代码中包含少量评论,但它正在运行可视化工具。你可以将它附加到你想要的任何玩家身上。

如何使用它:在xml布局中添加此视图,然后必须使用方法更新可视化器状态

public void updateVisualizer(byte[] bytes) {
    playerVisualizerView.updateVisualizer(bytes);
}

public void updatePlayerProgress(float percent) {
    playerVisualizerView.updatePlayerPercent(percent);
}

updateVisualizer中,您使用音频样本传递字节数组,并在updatePlayerProgress中动态传递百分比,同时播放音频样本。

用于将文件转换为字节,您可以使用此辅助方法

public static byte[] fileToBytes(File file) {
    int size = (int) file.length();
    byte[] bytes = new byte[size];
    try {
        BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
        buf.read(bytes, 0, bytes.length);
        buf.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bytes;
}

,例如(很快),它与Mosby库的外观如何:

public class AudioRecorderPresenter extends MvpBasePresenter<AudioRecorderView> {

public void onStopRecord() {
        // stopped and released MediaPlayer
        // ...
        // some preparation and saved audio file in audioFileName variable.

        getView().updateVisualizer(FileUtils.fileToBytes(new File(audioFileName)));
        }
    }
}

答案 1 :(得分:2)

我相信Scrobot's answer不起作用。它假定输入音频采用某种(非常特殊的)编码(5位深度的单通道/单线性PCM)。从波函数计算振幅的算法可能存在缺陷。如果将该算法与任何常用的音频文件格式一起使用,则只会得到随机数据。

事实是:事情有点复杂。

这是要实现OP的目标需要做的事情:

  1. 使用Android's MediaExtractor读取输入的音频文件(支持各种格式/编码)
  2. 使用Android's MediaCodec将输入音频编码解码为具有特定位深度(通常为16位)的线性PCM编码
    • 只有在执行此步骤后,您才能获得一个字节数组,可以线性读取并计算其幅度。
  3. 对PCM编码的数据应用响度测量。它们很多,有些更复杂(例如LUFS / LKFS),有些更基本(RMS)。让我们以RMS(=均方根)为例:
    1. 确定每条样品的数量。
    2. 读取单个条的所有样本。通常有2个通道,因此对于每个样本,您将获得PCM-16的2个短整数(16位)。
    3. 对于每个样本,计算所有通道的平均值。
    4. 也许您会希望以某种方式将值标准化,例如要获得介于-1和1之间的浮点值,可以除以(2 / /(1 << 16))
    5. 对每个样本求平方(因此在RMS中为“ S”)
    6. 计算所有样品的均值(均方根中的“ M”)
    7. 计算结果值的平方根(因此,RMS中的“ R”)
    8. 现在您将获得一个值,您可以根据该值来设置条形的高度。
    9. 对所有条重复步骤2-8。

要实现这一点是一项艰巨的任务。我找不到任何提供整个过程的库。但是至少Android的媒体API提供了读取任何格式的音频文件的算法。

注意:RMS被认为不是非常准确的响度度量。但这似乎产生的结果至少与您实际听到的声音有关。对于许多应用程序来说,它应该足够好。