1

我正在尝试开发像 Shazam 这样的 Android 应用程序。我搜索了 Shazam 在 Google 上的工作方式,我发现这是可以阅读的。如您所见,它首先录制歌曲。但我的录制代码有问题,因为 Android Studio 显示该代码带有红色下划线的错误。

这是我的代码:

private AudioFormat getFormat() {
    float sampleRate = 44100;
    int sampleSizeInBits = 16;
    int channels = 1;          //mono
    boolean signed = true;     //Indicates whether the data is signed or unsigned
    boolean bigEndian = true;  //Indicates whether the audio data is stored in big-endian or little-endian order
    return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
}

用于格式化录音。当我将该代码复制到主要活动中时,它显示错误如下:

在此处输入图像描述

当我将光标悬停在错误上时,它说“AudioFormat 在 android.media.AudioFormat 中不公开。无法从外部包访问”。我该如何解决?我关注的链接中的代码是否错误?我一直在搜索 Android 的教程代码来开发类似 Shazam 应用程序的东西。

为 Andrew Cheong 的回答编辑

我知道为什么因为Cheong的回答,所以我这样使用

private AudioFormat getFormat() {
        float sampleRate = 44100;
        int sampleSizeInBits = 16;
        int channels = 1;          //mono
        boolean signed = true;     //Indicates whether the data is signed or unsigned
        boolean bigEndian = true;  //Indicates whether the audio data is stored in big-endian or little-endian order

        return new AudioFormat.Builder().setSampleRate(Math.round(sampleRate)).build();
    }

但正如您在代码中看到的,我只能找到 setSampleRate() 来设置采样率。我找不到其他方法来设置 sampleSizeInBits、channels、signed 和 bigEndian。我不知道如何设置它们。如何设置其余变量?

4

1 回答 1

2

如果您查看AudioFormat 的文档,您可能会注意到它有一个“Builder Class”。

class   AudioFormat.Builder
        Builder class for AudioFormat objects. 

AudioFormat 对象的生成器类。使用这个类来配置和创建一个 AudioFormat 实例。通过设置格式特征,例如音频编码、通道掩码或采样率,您可以指示在使用此音频格式时,哪些与此设备上的默认行为不同。有关可用于配置 AudioFormat 实例的不同参数的完整说明,请参阅 AudioFormat。

这是build()方法。

这是应用程序设计中的一种“模式”,如果你不是设计模式的学生,这有点抽象/难以理解,但无论如何这里有一篇相关的文章。

于 2016-09-22T04:26:54.963 回答