Example usage for android.media AudioManager PROPERTY_OUTPUT_FRAMES_PER_BUFFER

List of usage examples for android.media AudioManager PROPERTY_OUTPUT_FRAMES_PER_BUFFER

Introduction

In this page you can find the example usage for android.media AudioManager PROPERTY_OUTPUT_FRAMES_PER_BUFFER.

Prototype

String PROPERTY_OUTPUT_FRAMES_PER_BUFFER

To view the source code for android.media AudioManager PROPERTY_OUTPUT_FRAMES_PER_BUFFER.

Click Source Link

Document

Used as a key for #getProperty to request the native or optimal output buffer size for this device's low latency output stream, in decimal PCM frames.

Usage

From source file:com.duongnx.ndk.examples.activities.NativeAudioActivity.java

/**
 * Called when the activity is first created.
 *//*from  w  w w  . j av  a2  s  . c  o m*/
@Override
@TargetApi(17)
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_native_audio);
    setTitle(Defines.NATIVE_AUDIO);
    assetManager = getAssets();

    // initialize native audio system
    createEngine();

    int sampleRate = 0;
    int bufSize = 0;
    /*
     * retrieve fast audio path sample rate and buf size; if we have it, we pass to native
     * side to create a player with fast audio enabled [ fast audio == low latency audio ];
     * IF we do not have a fast audio path, we pass 0 for sampleRate, which will force native
     * side to pick up the 8Khz sample rate.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        String nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
        sampleRate = Integer.parseInt(nativeParam);
        nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
        bufSize = Integer.parseInt(nativeParam);
    }
    createBufferQueueAudioPlayer(sampleRate, bufSize);

    // initialize URI spinner
    Spinner uriSpinner = (Spinner) findViewById(R.id.uri_spinner);
    ArrayAdapter<CharSequence> uriAdapter = ArrayAdapter.createFromResource(this, R.array.uri_spinner_array,
            android.R.layout.simple_spinner_item);
    uriAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    uriSpinner.setAdapter(uriAdapter);
    uriSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            URI = parent.getItemAtPosition(pos).toString();
        }

        public void onNothingSelected(AdapterView parent) {
            URI = null;
        }

    });

    // initialize button click handlers

    ((Button) findViewById(R.id.hello)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_HELLO, 5);
        }
    });

    ((Button) findViewById(R.id.android)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_ANDROID, 7);
        }
    });

    ((Button) findViewById(R.id.sawtooth)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_SAWTOOTH, 1);
        }
    });

    ((Button) findViewById(R.id.reverb)).setOnClickListener(new OnClickListener() {
        boolean enabled = false;

        public void onClick(View view) {
            enabled = !enabled;
            if (!enableReverb(enabled)) {
                enabled = !enabled;
            }
        }
    });

    ((Button) findViewById(R.id.embedded_soundtrack)).setOnClickListener(new OnClickListener() {
        boolean created = false;

        public void onClick(View view) {
            if (!created) {
                created = createAssetAudioPlayer(assetManager, "background.mp3");
            }
            if (created) {
                isPlayingAsset = !isPlayingAsset;
                setPlayingAssetAudioPlayer(isPlayingAsset);
            }
        }
    });

    // native uriPlayer is broken in android 21 and over, internal bug id: b/29321867
    // will re-open after it is fixed in later OSes
    if (Build.VERSION.SDK_INT <= 19) {
        ((Button) findViewById(R.id.uri_soundtrack)).setOnClickListener(new OnClickListener() {
            boolean created = false;

            public void onClick(View view) {
                if (!created && URI != null) {
                    created = createUriAudioPlayer(URI);
                }
            }
        });

        ((Button) findViewById(R.id.pause_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                setPlayingUriAudioPlayer(false);
            }
        });

        ((Button) findViewById(R.id.play_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                setPlayingUriAudioPlayer(true);
            }
        });

        ((Button) findViewById(R.id.loop_uri)).setOnClickListener(new OnClickListener() {
            boolean isLooping = false;

            public void onClick(View view) {
                isLooping = !isLooping;
                setLoopingUriAudioPlayer(isLooping);
            }
        });

        ((Button) findViewById(R.id.mute_left_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setChannelMuteUriAudioPlayer(0, muted);
            }
        });

        ((Button) findViewById(R.id.mute_right_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setChannelMuteUriAudioPlayer(1, muted);
            }
        });

        ((Button) findViewById(R.id.solo_left_uri)).setOnClickListener(new OnClickListener() {
            boolean soloed = false;

            public void onClick(View view) {
                soloed = !soloed;
                setChannelSoloUriAudioPlayer(0, soloed);
            }
        });

        ((Button) findViewById(R.id.solo_right_uri)).setOnClickListener(new OnClickListener() {
            boolean soloed = false;

            public void onClick(View view) {
                soloed = !soloed;
                setChannelSoloUriAudioPlayer(1, soloed);
            }
        });

        ((Button) findViewById(R.id.mute_uri)).setOnClickListener(new OnClickListener() {
            boolean muted = false;

            public void onClick(View view) {
                muted = !muted;
                setMuteUriAudioPlayer(muted);
            }
        });

        ((Button) findViewById(R.id.enable_stereo_position_uri)).setOnClickListener(new OnClickListener() {
            boolean enabled = false;

            public void onClick(View view) {
                enabled = !enabled;
                enableStereoPositionUriAudioPlayer(enabled);
            }
        });

        ((Button) findViewById(R.id.channels_uri)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                if (numChannelsUri == 0) {
                    numChannelsUri = getNumChannelsUriAudioPlayer();
                }
                Toast.makeText(NativeAudioActivity.this, "Channels: " + numChannelsUri, Toast.LENGTH_SHORT)
                        .show();
            }
        });

        ((SeekBar) findViewById(R.id.volume_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int lastProgress = 100;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                    throw new AssertionError();
                }
                lastProgress = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                int attenuation = 100 - lastProgress;
                int millibel = attenuation * -50;
                setVolumeUriAudioPlayer(millibel);
            }
        });

        ((SeekBar) findViewById(R.id.pan_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int lastProgress = 100;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                    throw new AssertionError();
                }
                lastProgress = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                int permille = (lastProgress - 50) * 20;
                setStereoPositionUriAudioPlayer(permille);
            }
        });
    } else {
        int[] uriIds = { R.id.uri_soundtrack, R.id.pause_uri, R.id.play_uri, R.id.loop_uri, R.id.mute_left_uri,
                R.id.mute_right_uri, R.id.solo_left_uri, R.id.solo_right_uri, R.id.mute_uri,
                R.id.enable_stereo_position_uri, R.id.channels_uri, R.id.volume_uri, R.id.pan_uri,
                R.id.uri_spinner, };
        for (int id : uriIds)
            findViewById(id).setVisibility(View.GONE);
    }

    ((Button) findViewById(R.id.record)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            int status = ActivityCompat.checkSelfPermission(NativeAudioActivity.this,
                    Manifest.permission.RECORD_AUDIO);
            if (status != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(NativeAudioActivity.this,
                        new String[] { Manifest.permission.RECORD_AUDIO }, AUDIO_ECHO_REQUEST);
                return;
            }
            recordAudio();
        }
    });

    ((Button) findViewById(R.id.playback)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_PLAYBACK, 3);
        }
    });

}

From source file:com.example.nativeaudio.NativeAudio.java

/** Called when the activity is first created. */
@Override//from  w w  w  .  j a v  a2  s . c o  m
@TargetApi(17)
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    Log.d(TAG, "onCreate ----------- ");

    assetManager = getAssets();

    /*
    Ctrl+O ?
    Ctrl+I ?
            
    Ctrl+N /?
    Ctrl+Shift+N 
    Ctrl+Shift+ALt+N ?
            
            
    Ctrl+Space ???
    Ctrl+Shift+Space ?
    Ctrl+Shift+Enter (? ?; )
    Ctrl+P ??
            
    Alt+Enter ?/?/
            
    Ctrl+J ?? ( for foreach Toast system.out.println) logm logr loge
      */

    // initialize native audio system
    createEngine();

    int sampleRate = 0;
    int bufSize = 0;
    /*
     * retrieve fast audio path sample rate and buf size; if we have it, we pass to native
     * side to create a player with fast audio enabled [ fast audio == low latency audio ];
     * IF we do not have a fast audio path, we pass 0 for sampleRate, which will force native
     * side to pick up the 8Khz sample rate.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        String nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
        sampleRate = Integer.parseInt(nativeParam);
        nativeParam = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
        bufSize = Integer.parseInt(nativeParam); // buffer?

        PackageManager pm = getPackageManager();
        boolean claimsFeature = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);

        // ?5 OUTPUT_SAMPLE_RATE = 48000 OUTPUT_FRAMES_PER_BUFFER = 192 FEATURE_AUDIO_LOW_LATENCY = false
        // MTK MT6735  OUTPUT_SAMPLE_RATE = 44100 OUTPUT_FRAMES_PER_BUFFER = 1024 FEATURE_AUDIO_LOW_LATENCY = false
        Log.d(TAG, "OUTPUT_SAMPLE_RATE = " + sampleRate + " OUTPUT_FRAMES_PER_BUFFER = " + bufSize
                + " FEATURE_AUDIO_LOW_LATENCY = " + claimsFeature);
    }

    //  buffer queue AudioPlayer Demo
    createBufferQueueAudioPlayer(sampleRate, bufSize);

    // initialize URI spinner
    Spinner uriSpinner = (Spinner) findViewById(R.id.uri_spinner);
    ArrayAdapter<CharSequence> uriAdapter = ArrayAdapter.createFromResource(this,
            R.array.local_uri_spinner_array,
            /* R.array.uri_spinner_array, */
            android.R.layout.simple_spinner_item);
    uriAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    uriSpinner.setAdapter(uriAdapter);
    uriSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            URI = parent.getItemAtPosition(pos).toString();
            /* ? ?
              <string-array name="uri_spinner_array">
                <item>http://upload.wikimedia.org/wikipedia/commons/6/6d/Banana.ogg</item>
                <item>http://www.freesound.org/data/previews/18/18765_18799-lq.mp3</item>
              </string-array>
             */
        }

        public void onNothingSelected(AdapterView parent) {
            URI = null;
        }

    });

    // initialize button click handlers

    ((Button) findViewById(R.id.hello)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_HELLO, 2);
        }
    });

    ((Button) findViewById(R.id.android)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_ANDROID, 7);
        }
    });

    ((Button) findViewById(R.id.sawtooth)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_SAWTOOTH, 1);
        }
    });

    ((Button) findViewById(R.id.reverb)).setOnClickListener(new OnClickListener() {
        boolean enabled = false;

        public void onClick(View view) {
            enabled = !enabled;
            if (!enableReverb(enabled)) {
                enabled = !enabled;
            }
        }
    });

    //  AssertManager APK?mp3
    //
    ((Button) findViewById(R.id.embedded_soundtrack)).setOnClickListener(new OnClickListener() {
        boolean created = false;

        public void onClick(View view) {
            if (!created) {
                created = createAssetAudioPlayer(assetManager, "withus.mp3");
            }
            if (created) {
                // URI AudioPlayer Demo ?
                // URI AudioPlayer Demo ? ?play pause
                // Assert/fd AudioPlayer  Demo ?
                isPlayingAsset = !isPlayingAsset;
                setPlayingAssetAudioPlayer(isPlayingAsset);
            }
        }
    });

    ((Button) findViewById(R.id.uri_soundtrack)).setOnClickListener(new OnClickListener() {
        boolean created = false;

        public void onClick(View view) {
            if (!created && URI != null) {
                Log.d(TAG, " uri_soundtrack create URI Audio Player URI " + URI);
                //URI = "file:///mnt/sdcard/xxx.3gp" ;
                //URI = "file:///mnt/sdcard/Banana.ogg" ;
                created = createUriAudioPlayer(URI);
            }
        }
    });

    ((Button) findViewById(R.id.pause_uri)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            Log.d(TAG, " setPlayingUriAudioPlayer  pause URI ");
            setPlayingUriAudioPlayer(false);
        }
    });

    ((Button) findViewById(R.id.play_uri)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            Log.d(TAG, " setPlayingUriAudioPlayer  play URI ");
            setPlayingUriAudioPlayer(true);
        }
    });

    ((Button) findViewById(R.id.loop_uri)).setOnClickListener(new OnClickListener() {
        boolean isLooping = false;

        public void onClick(View view) {
            isLooping = !isLooping;
            setLoopingUriAudioPlayer(isLooping);

        }
    });

    ((Button) findViewById(R.id.mute_left_uri)).setOnClickListener(new OnClickListener() {
        boolean muted = false;

        public void onClick(View view) {
            muted = !muted;
            setChannelMuteUriAudioPlayer(0, muted);
        }
    });

    ((Button) findViewById(R.id.mute_right_uri)).setOnClickListener(new OnClickListener() {
        boolean muted = false;

        public void onClick(View view) {
            muted = !muted;
            setChannelMuteUriAudioPlayer(1, muted);
        }
    });

    ((Button) findViewById(R.id.solo_left_uri)).setOnClickListener(new OnClickListener() {
        boolean soloed = false;

        public void onClick(View view) {
            soloed = !soloed;
            setChannelSoloUriAudioPlayer(0, soloed);
        }
    });

    ((Button) findViewById(R.id.solo_right_uri)).setOnClickListener(new OnClickListener() {
        boolean soloed = false;

        public void onClick(View view) {
            soloed = !soloed;
            setChannelSoloUriAudioPlayer(1, soloed);
        }
    });

    ((Button) findViewById(R.id.mute_uri)).setOnClickListener(new OnClickListener() {
        boolean muted = false;

        public void onClick(View view) {
            muted = !muted;
            setMuteUriAudioPlayer(muted);
        }
    });

    /*
    *  ???? ?  Stereo Panning
    *  https://developer.android.com/ndk/guides/audio/opensl-prog-notes.html#panning
    *
    * */
    ((Button) findViewById(R.id.enable_stereo_position_uri)).setOnClickListener(new OnClickListener() {
        boolean enabled = false;

        public void onClick(View view) {
            enabled = !enabled;
            enableStereoPositionUriAudioPlayer(enabled);
        }
    });

    // ??  ?AudioPlayer ??? ?SetPlayState???
    ((Button) findViewById(R.id.channels_uri)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if (numChannelsUri == 0) {
                numChannelsUri = getNumChannelsUriAudioPlayer();
            }
            Toast.makeText(NativeAudio.this, "Channels: " + numChannelsUri, Toast.LENGTH_SHORT).show();
        }
    });

    // ??
    ((SeekBar) findViewById(R.id.volume_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        int lastProgress = 100;

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                throw new AssertionError();
            }
            lastProgress = progress;
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            int attenuation = 100 - lastProgress;
            int millibel = attenuation * -50; // 100 * -50  ~  0
            setVolumeUriAudioPlayer(millibel);
        }
    });

    ((SeekBar) findViewById(R.id.pan_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        int lastProgress = 100;

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                throw new AssertionError();
            }
            lastProgress = progress;
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            // ?? ?
            // ? ?  ?<50  >50 ?
            int permille = (lastProgress - 50) * 20;
            setStereoPositionUriAudioPlayer(permille);
        }
    });

    ((SeekBar) findViewById(R.id.playback_rate_uri)).setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        int lastProgress = 100;

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (BuildConfig.DEBUG && !(progress >= 0 && progress <= 100)) {
                throw new AssertionError();
            }
            lastProgress = progress;
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        public void onStopTrackingTouch(SeekBar seekBar) {

            /*
                    0 ----- 50 ---- 100
                  -1000 --- 0 ---- 1000
             */
            int permille = lastProgress * (1000 - -1000) / 100 + (-1000);
            setPlaybackRateUriAudioPlayer(permille);
        }
    });

    ((Button) findViewById(R.id.record)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            //                int status = ActivityCompat.checkSelfPermission(NativeAudio.this,
            //                        Manifest.permission.RECORD_AUDIO);
            //                if (status != PackageManager.PERMISSION_GRANTED) {
            //                    ActivityCompat.requestPermissions(
            //                            NativeAudio.this,
            //                            new String[]{Manifest.permission.RECORD_AUDIO},
            //                            AUDIO_ECHO_REQUEST);
            //                    return;
            //                }
            recordAudio();
        }
    });

    ((Button) findViewById(R.id.playback)).setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            // ignore the return value
            selectClip(CLIP_PLAYBACK, 3);
        }
    });

}

From source file:com.ece420.lab3.MainActivity.java

private void queryNativeAudioParameters() {
    AudioManager myAudioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    nativeSampleRate = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
    nativeSampleBufSize = myAudioMgr.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
    int recBufSize = AudioRecord.getMinBufferSize(Integer.parseInt(nativeSampleRate),
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    supportRecording = true;/* w w w. j  a  v a2s  . co m*/
    if (recBufSize == AudioRecord.ERROR || recBufSize == AudioRecord.ERROR_BAD_VALUE) {
        supportRecording = false;
    }
}

From source file:com.levien.audiobuffersize.AudioBufferSize.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
void getJbMr1Params(AudioParams params) {
    AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    String sr = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
    String bs = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
    params.confident = true;// w  w w .  j  a v  a2  s.co  m
    params.sampleRate = Integer.parseInt(sr);
    params.bufferSize = Integer.parseInt(bs);
    logUI("from platform: " + params);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onCreate() {
    super.onCreate();
    FileLog.d("=============== VoIPService STARTING ===============");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
            && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) {
        int outFramesPerBuffer = Integer
                .parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
        VoIPController.setNativeBufferSize(outFramesPerBuffer);
    } else {//  w  w w . j ava  2 s  .c  o m
        VoIPController.setNativeBufferSize(
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
                        / 2);
    }
    final SharedPreferences preferences = getSharedPreferences("mainconfig", MODE_PRIVATE);
    VoIPServerConfig.setConfig(preferences.getString("voip_server_config", "{}"));
    if (System.currentTimeMillis() - preferences.getLong("voip_server_config_updated", 0) > 24 * 3600000) {
        ConnectionsManager.getInstance().sendRequest(new TLRPC.TL_phone_getCallConfig(), new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                if (error == null) {
                    String data = ((TLRPC.TL_dataJSON) response).data;
                    VoIPServerConfig.setConfig(data);
                    preferences.edit().putString("voip_server_config", data)
                            .putLong("voip_server_config_updated",
                                    BuildConfig.DEBUG ? 0 : System.currentTimeMillis())
                            .apply();
                }
            }
        });
    }
    try {
        controller = new VoIPController();
        controller.setConnectionStateListener(this);
        controller.setConfig(MessagesController.getInstance().callPacketTimeout / 1000.0,
                MessagesController.getInstance().callConnectTimeout / 1000.0,
                preferences.getInt("VoipDataSaving", VoIPController.DATA_SAVING_NEVER));

        cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
        cpuWakelock.acquire();

        btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ACTION_HEADSET_PLUG);
        if (btAdapter != null) {
            filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        }
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(getPackageName() + ".END_CALL");
        filter.addAction(getPackageName() + ".DECLINE_CALL");
        filter.addAction(getPackageName() + ".ANSWER_CALL");
        registerReceiver(receiver, filter);

        ConnectionsManager.getInstance().setAppPaused(false, false);

        soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
        spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
        spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
        spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
        spEndId = soundPool.load(this, R.raw.voip_end, 1);
        spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

        am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

        if (btAdapter != null && btAdapter.isEnabled()) {
            int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED);
            if (headsetState == BluetoothProfile.STATE_CONNECTED)
                am.setBluetoothScoOn(true);
            for (StateListener l : stateListeners)
                l.onAudioSettingsChanged();
        }

        NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    } catch (Exception x) {
        FileLog.e("error initializing voip controller", x);
        callFailed();
    }
}