Search code examples
androidaudiofftaudioformat

AudioFormat is not public in android.media.AudioFormat


I am trying to develop an Android App like Shazam. I searched how Shazam worked on Google and I found this to read. As you can see, it records the song first. But I am having the problem with its recording code because Android Studio is showing error with red underline for that code.

Here is my code:

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);
}

Is is used to format the audio recording. When I copy that code into main activity, it shows the error as follow:

enter image description here

When I hover the cursor the on error, it is saying "AudioFormat is not public in android.media.AudioFormat. Cannot be accessed from outside package". How can I fix it? Is the code in the link I am following wrong? I have been searching tutorial code for Android to develop something like Shazam app.

Edited for Andrew Cheong's Answer

I knew why because of Cheong's answer and so I use like this

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();
    }

But as you can see in the code, I can only find setSampleRate() to set sample rate. I cannot find others method to set sampleSizeInBits, channels, signed and bigEndian. I don't know how to set them. How can I set the rest of the variables?


Solution

  • If you look at the documentation for AudioFormat, you might notice that it has a "Builder Class."

    class   AudioFormat.Builder
            Builder class for AudioFormat objects. 
    

    Builder class for AudioFormat objects. Use this class to configure and create an AudioFormat instance. By setting format characteristics such as audio encoding, channel mask or sample rate, you indicate which of those are to vary from the default behavior on this device wherever this audio format is used. See AudioFormat for a complete description of the different parameters that can be used to configure an AudioFormat instance.

    Here's the build() method.

    This is a kind of "pattern" in application design, and it's a little abstract / difficult to understand if you're not a student of design patterns, but here's a relevant article anyway.