package com.dowse.base.audio;

import android.media.AudioTrack;
import android.util.Log;

/* loaded from: ds_base_2.0.9_23030112.aar:classes.jar:com/dowse/base/audio/AudioPlayer.class */
public class AudioPlayer {
    private static final String TAG = "AudioPlayer";
    private static final int DEFAULT_STREAM_TYPE = 3;
    private static final int DEFAULT_SAMPLE_RATE = 8000;
    private static final int DEFAULT_CHANNEL_CONFIG = 4;
    private static final int DEFAULT_AUDIO_FORMAT = 2;
    private static final int DEFAULT_PLAY_MODE = 1;
    private boolean mIsPlayStarted = false;
    private int mMinBufferSize = 0;
    private AudioTrack mAudioTrack;

    public boolean startPlayer() {
        return startPlayer(3, DEFAULT_SAMPLE_RATE, DEFAULT_CHANNEL_CONFIG, 2);
    }

    public boolean startPlayer(int streamType, int sampleRateInHz, int channelConfig, int audioFormat) {
        if (this.mIsPlayStarted) {
            Log.e(TAG, "Player already started !");
            return false;
        }
        this.mMinBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
        if (this.mMinBufferSize == -2) {
            Log.e(TAG, "Invalid parameter !");
            return false;
        }
        Log.d(TAG, "getMinBufferSize = " + this.mMinBufferSize + " bytes !");
        this.mAudioTrack = new AudioTrack(streamType, sampleRateInHz, channelConfig, audioFormat, this.mMinBufferSize, 1);
        if (this.mAudioTrack.getState() == 0) {
            Log.e(TAG, "AudioTrack initialize fail !");
            return false;
        }
        this.mIsPlayStarted = true;
        Log.d(TAG, "Start audio player success !");
        return true;
    }

    public int getMinBufferSize() {
        return this.mMinBufferSize;
    }

    public boolean stopPlayer() {
        if (!this.mIsPlayStarted) {
            return false;
        }
        if (this.mAudioTrack.getPlayState() == 3) {
            this.mAudioTrack.stop();
        }
        this.mAudioTrack.release();
        this.mIsPlayStarted = false;
        Log.d(TAG, "Stop audio player success !");
        return true;
    }

    public boolean play(byte[] audioData, int offsetInBytes, int sizeInBytes) {
        if (!this.mIsPlayStarted) {
            Log.e(TAG, "Player not started !");
            return false;
        } else if (sizeInBytes < this.mMinBufferSize) {
            Log.e(TAG, "audio data is not enough !");
            return false;
        } else {
            if (this.mAudioTrack.write(audioData, offsetInBytes, sizeInBytes) != sizeInBytes) {
                Log.e(TAG, "Could not write all the samples to the audio device !");
            }
            this.mAudioTrack.play();
            Log.d(TAG, "OK, Played " + sizeInBytes + " bytes !");
            return true;
        }
    }
}
