android.media.AudioTrack.play()

Here are the examples of the java api android.media.AudioTrack.play() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

65 Examples 7

19 Source : MainActivity.java
with Apache License 2.0
from z13538657403

private void playAudio(File audioFile) {
    Log.d("MainActivity", "lu yin kaishi");
    int streamType = AudioManager.STREAM_MUSIC;
    int simpleRate = 44100;
    int channelConfig = AudioFormat.CHANNEL_OUT_STEREO;
    int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    int mode = AudioTrack.MODE_STREAM;
    int minBufferSize = AudioTrack.getMinBufferSize(simpleRate, channelConfig, audioFormat);
    AudioTrack audioTrack = new AudioTrack(streamType, simpleRate, channelConfig, audioFormat, Math.max(minBufferSize, BUFFER_SIZE), mode);
    audioTrack.play();
    Log.d(TAG, minBufferSize + " is the min buffer size , " + BUFFER_SIZE + " is the read buffer size");
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(audioFile);
        int read;
        while ((read = inputStream.read(mBuffer)) > 0) {
            Log.d("MainActivity", "lu yin kaishi11111");
            audioTrack.write(mBuffer, 0, read);
        }
    } catch (RuntimeException | IOException e) {
        e.printStackTrace();
    }
}

19 Source : OBAudioBufferPlayer.java
with Apache License 2.0
from XPRIZE

public // call only after prepare!!!
void play() {
    audioTrack.setPlaybackPositionUpdateListener(new AudioTrack.OnPlaybackPositionUpdateListener() {

        @Override
        public void onMarkerReached(AudioTrack track) {
            trackFinished();
        }

        @Override
        public void onPeriodicNotification(AudioTrack track) {
        }
    });
    audioTrack.play();
    state = OBAP_PLAYING;
}

19 Source : Spirit3AudioService.java
with GNU General Public License v3.0
from vladislav805

private void pcm_write_start() {
    try {
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, mSampleRate, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, mBufferSizeInBytes, AudioTrack.MODE_STREAM);
        // java.lang.IllegalStateException: play() called on uninitialized AudioTrack.
        mAudioTrack.play();
    } catch (Throwable e) {
        e.printStackTrace();
        return;
    }
    if (pcm_write_thread_active) {
        return;
    }
    pcm_write_thread_active = true;
    pcm_write_thread = new Thread(pcm_write_runnable, "pcm_write");
    pcm_write_thread.start();
}

19 Source : AudioPlayer.java
with MIT License
from ThinkKeep

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

19 Source : AudioTrackJNI.java
with GNU General Public License v2.0
from TelePlusDev

public void start() {
    if (thread == null) {
        startThread();
    } else {
        audioTrack.play();
    }
}

19 Source : DefaultAudioSink.java
with GNU General Public License v2.0
from TelePlusDev

@Override
public void play() {
    playing = true;
    if (isInitialized()) {
        audioTrackPositionTracker.start();
        audioTrack.play();
    }
}

19 Source : AudioSink.java
with GNU General Public License v2.0
from takyonxxx

@Override
public void run() {
    SamplePacket packet;
    SamplePacket filteredPacket;
    SamplePacket tempPacket = new SamplePacket(packetSize);
    float[] floatPacket;
    short[] shortPacket = new short[packetSize];
    Log.i(LOGTAG, "AudioSink started. (Thread: " + this.getName() + ")");
    // start audio playback:
    audioTrack.play();
    // Continuously write the data from the queue to the audio track:
    while (!stopRequested) {
        try {
            // Get the next packet from the queue
            packet = inputQueue.poll(1000, TimeUnit.MILLISECONDS);
            if (packet == null) {
                // Log.d(LOGTAG, "run: Queue is empty. skip this round");
                continue;
            }
            // apply audio filter (decimation)
            if (packet.getSampleRate() > this.sampleRate) {
                applyAudioFilter(packet, tempPacket);
                filteredPacket = tempPacket;
            } else
                filteredPacket = packet;
            // Convert doubles to shorts [expect doubles to be in [-1...1]
            floatPacket = filteredPacket.re();
            for (int i = 0; i < filteredPacket.size(); i++) {
                shortPacket[i] = (short) (floatPacket[i] * 32767);
            }
            // Write it to the audioTrack:
            if (audioTrack.write(shortPacket, 0, filteredPacket.size()) != filteredPacket.size()) {
                Log.e(LOGTAG, "run: write() returned with error! stop");
                stopRequested = true;
            }
            // Return the buffer to the output queue
            outputQueue.offer(packet);
        } catch (InterruptedException e) {
            Log.e(LOGTAG, "run: Interrupted while polling from queue. stop");
            stopRequested = true;
        }
    }
    // stop audio playback:
    audioTrack.stop();
    this.stopRequested = true;
    Log.i(LOGTAG, "AudioSink stopped. (Thread: " + this.getName() + ")");
}

19 Source : Metronome.java
with GNU General Public License v3.0
from ryotayama

public void play() {
    stop();
    if (mThread != null) {
        try {
            mThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    mAudioTrack.play();
    mPlaying = true;
    mRunnable = new Runnable() {

        @Override
        public void run() {
            while (mPlaying) {
                int beatLength = (int) Math.round((60.0 / mBpm) * mAudioTrack.getSampleRate());
                beatLength = beatLength * 2;
                int soundLength = mSound.length > beatLength ? beatLength : mSound.length;
                mAudioTrack.write(mSound, 0, soundLength);
                byte[] space = buildSpace(beatLength, soundLength);
                mAudioTrack.write(space, 0, space.length);
            }
        }
    };
    mThread = new Thread(mRunnable);
    mThread.start();
}

19 Source : AudioTrackOutputStream.java
with BSD 3-Clause "New" or "Revised" License
from ridi

@CalledByNative
void start(long nativeAudioTrackOutputStream) {
    Log.d(TAG, "AudioTrackOutputStream.start()");
    if (mWorkerThread != null)
        return;
    mNativeAudioTrackOutputStream = nativeAudioTrackOutputStream;
    mTotalReadFrames = 0;
    mReadBuffer = allocateAlignedByteBuffer(mBufferSizeInBytes, CHANNEL_ALIGNMENT);
    mAudioTrack.play();
    mWorkerThread = new WorkerThread();
    mWorkerThread.start();
}

19 Source : Synth.java
with GNU General Public License v3.0
from quaap

@Override
public void run() {
    mRun = true;
    try {
        mAudioTrack.play();
        int entries = (int) (sampleRate / mSnipsPerSample);
        short[] data = new short[entries];
        while (mRun) {
            if (mPause) {
                sleep(100);
            } else {
                Arrays.fill(data, (short) 0);
                getData(data);
                write(data);
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        close();
    }
}

19 Source : AudioOutput.java
with Apache License 2.0
from olgamiller

@Override
public void init(int samples) {
    // 2.5 seconds of buffer
    mAudioBuffer = new short[(5 * (int) mSampleRate) / 2];
    mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, (int) mSampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, mAudioBuffer.length * 2, AudioTrack.MODE_STREAM);
    mAudioTrack.play();
}

19 Source : Audio.java
with GNU General Public License v3.0
from NeoTerm

public int initAudio(int rate, int channels, int encoding, int bufSize) {
    if (mAudio == null) {
        channels = (channels == 1) ? AudioFormat.CHANNEL_CONFIGURATION_MONO : AudioFormat.CHANNEL_CONFIGURATION_STEREO;
        encoding = (encoding == 1) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
        mVirtualBufSize = bufSize;
        if (AudioTrack.getMinBufferSize(rate, channels, encoding) > bufSize)
            bufSize = AudioTrack.getMinBufferSize(rate, channels, encoding);
        if (Globals.AudioBufferConfig != 0) {
            // application's choice - use minimal buffer
            bufSize = (int) ((float) bufSize * (((float) (Globals.AudioBufferConfig - 1) * 2.5f) + 1.0f));
            mVirtualBufSize = bufSize;
        }
        mAudioBuffer = new byte[bufSize];
        mAudio = new AudioTrack(AudioManager.STREAM_MUSIC, rate, channels, encoding, bufSize, AudioTrack.MODE_STREAM);
        mAudio.play();
    }
    return mVirtualBufSize;
}

19 Source : Audio.java
with GNU General Public License v3.0
from NeoTerm

public int resumeAudioPlayback() {
    if (mAudio != null) {
        mAudio.play();
    }
    if (mRecordThread != null) {
        mRecordThread.resumeRecording();
    }
    return 1;
}

19 Source : TuneThread.java
with MIT License
from Lokarzz

@Override
public void run() {
    super.run();
    isRunning = true;
    int buffsize = AudioTrack.getMinBufferSize(sr, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
    // create an audiotrack object
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sr, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, buffsize, AudioTrack.MODE_STREAM);
    short[] samples = new short[buffsize];
    int amp = 10000;
    double twopi = 8. * Math.atan(1.);
    double ph = 0.0;
    // start audio
    audioTrack.play();
    // synthesis loop
    while (isRunning) {
        double fr = tuneFreq;
        for (int i = 0; i < buffsize; i++) {
            samples[i] = (short) (amp * Math.sin(ph));
            ph += twopi * fr / sr;
        }
        audioTrack.write(samples, 0, buffsize);
    }
    audioTrack.stop();
    audioTrack.release();
}

19 Source : UPlayerPcm.java
with Apache License 2.0
from KosmoSakura

/**
 * 播放,使用stream模式
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void playPcm() {
    final int minBufferSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
    audioTrack = new AudioTrack(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build(), new AudioFormat.Builder().setSampleRate(44100).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build(), minBufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE);
    audioTrack.play();
    File file = new File(dirPcm);
    try {
        fileInputStream = new FileInputStream(file);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    byte[] tempBuffer = new byte[minBufferSize];
                    while (fileInputStream.available() > 0) {
                        int readCount = fileInputStream.read(tempBuffer);
                        if (readCount == AudioTrack.ERROR_INVALID_OPERATION || readCount == AudioTrack.ERROR_BAD_VALUE) {
                            continue;
                        }
                        if (readCount != 0 && readCount != -1) {
                            audioTrack.write(tempBuffer, 0, readCount);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

19 Source : AudioTrackPlayerImpl.java
with Apache License 2.0
from dueros

@Override
public void resume() {
    if (mCurrentState == PlayState.PAUSED) {
        mAudioTrack.play();
        mCurrentState = PlayState.PLAYING;
        firePlaying();
    }
}

19 Source : MidiDriver.java
with GNU Lesser General Public License v2.1
from cyclopsian

// Process MidiDriver
private void processMidi() {
    int status = 0;
    int size = 0;
    // Init midi
    if ((size = init()) == 0)
        return;
    buffer = new short[size];
    // Create audio track
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE, AudioTrack.MODE_STREAM);
    // Check audiotrack
    if (audioTrack == null) {
        shutdown();
        return;
    }
    // Check state
    int state = audioTrack.getState();
    if (state != AudioTrack.STATE_INITIALIZED) {
        audioTrack.release();
        shutdown();
        return;
    }
    // Call listener
    if (listener != null)
        listener.onMidiStart();
    // Play track
    audioTrack.play();
    // Keep running until stopped
    while (thread != null) {
        // Render the audio
        if (render(buffer) == 0)
            break;
        // Write audio to audiotrack
        status = audioTrack.write(buffer, 0, buffer.length);
        if (status < 0)
            break;
    }
    // Render and write the last bit of audio
    if (status > 0)
        if (render(buffer) > 0)
            audioTrack.write(buffer, 0, buffer.length);
    // Shut down audio
    shutdown();
    audioTrack.release();
}

19 Source : PcmPlayer.java
with MIT License
from ashqal

public void start() {
    trackplayer.play();
}

19 Source : PcmPlayer.java
with MIT License
from ashqal

public void resume() {
    trackplayer.play();
}

19 Source : AudioTrackManagerDualStreamType.java
with Apache License 2.0
from ApolloAuto

@Override
public void resumeMusicAudioTrack() {
    // some times, initMusicAudioTrack() maybe fail
    if (mMusicAudioTrack == null) {
        reInitAudioTrack();
    }
    if ((mMusicAudioTrack != null) && (mMusicAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)) {
        try {
            mMusicAudioTrack.play();
        } catch (IllegalStateException e) {
            LogUtil.e(FTAG, "resume media play failed!");
            informMusicPause();
            e.printStackTrace();
        }
    }
    LogUtil.e("Audio-AudioTrackManagerDualStreamType", "resumeMusicAudioTrack");
    if (getMusicAudioTrackFocus() == 0) {
        setMediaAudioFocusStatus(true);
    } else {
        setMediaAudioFocusStatus(false);
        getAudioFocusFailedWhenResume = true;
    }
}

19 Source : AudioTrackManagerDualStreamType.java
with Apache License 2.0
from ApolloAuto

@Override
public void initTTSAudioTrack(int ttsType, int sampleRate, int channelConfig, int sampleFormat) {
    int tChannelConfig;
    int tSampleFormat;
    int audioMinBufSizeLocal;
    // if (mTTSAudioTrack != null) {
    // mTTSAudioTrack.pause();
    // mTTSAudioTrack.flush();
    // }
    // request AudioFocus for TTS
    if (getTTSAudioTrackFocus(ttsType) == 0) {
        setTTSAudioFocusStatus(true);
    } else {
        setTTSAudioFocusStatus(false);
    }
    if (mTTSSampleRate != sampleRate || mTTSChannelConfig != channelConfig || mTTSSampleFormat != sampleFormat || mTTSAudioTrack == null) {
        mTTSSampleRate = sampleRate;
        mTTSChannelConfig = channelConfig;
        mTTSSampleFormat = sampleFormat;
        releaseTTSAudioTrack();
        // avoid crush
        if (mTTSSampleRate <= 0) {
            mTTSSampleRate = 16000;
        }
        if (mTTSChannelConfig == 2) {
            tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
        } else if (mTTSChannelConfig == 1) {
            tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
        } else {
            tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
        }
        if (sampleFormat == 8) {
            tSampleFormat = AudioFormat.ENCODING_PCM_8BIT;
        } else {
            tSampleFormat = AudioFormat.ENCODING_PCM_16BIT;
        }
        audioMinBufSizeLocal = AudioTrack.getMinBufferSize(mTTSSampleRate, tChannelConfig, tSampleFormat);
        // audioMinBufSizeLocal = PCMPlayerUtils.TTS_AUDIO_TRACK_BUFFER_SIZE;
        LogUtil.d(TAG, "audioMinBufSizeLocal= " + audioMinBufSizeLocal);
        try {
            LogUtil.d(TAG, "init audio track->mStreamType: " + mStreamType);
            mTTSAudioTrack = new AudioTrack(mStreamType, mTTSSampleRate, tChannelConfig, tSampleFormat, audioMinBufSizeLocal, AudioTrack.MODE_STREAM);
        } catch (IllegalArgumentException e) {
            mTTSAudioTrack = null;
            e.printStackTrace();
        }
        if (mTTSAudioTrack != null) {
            try {
                mTTSAudioTrack.play();
            } catch (IllegalStateException e) {
                mTTSAudioTrack = null;
                LogUtil.e(FTAG, "init tts audio track failed!");
                e.printStackTrace();
            }
        }
    }
}

19 Source : AudioTrackManagerDualStreamType.java
with Apache License 2.0
from ApolloAuto

@Override
public void initMusicAudioTrack(int sampleRate, int channelConfig, int sampleFormat) {
    int tChannelConfig;
    int tSampleFormat;
    int audioMinBufSizeLocal;
    // request Audio Focus
    if (getMusicAudioTrackFocus() == 0) {
        setMediaAudioFocusStatus(true);
    } else {
        setMediaAudioFocusStatus(false);
    }
    mMusicSampleRate = sampleRate;
    mMusicChannelConfig = channelConfig;
    mMusicSampleFormat = sampleFormat;
    releaseMusicAudioTrack();
    // avoid crush
    if (mMusicSampleRate <= 0) {
        mMusicSampleRate = 44100;
    }
    if (mMusicChannelConfig == 2) {
        tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
    } else if (mMusicChannelConfig == 1) {
        tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
    } else {
        tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
    }
    if (sampleFormat == 8) {
        tSampleFormat = AudioFormat.ENCODING_PCM_8BIT;
    } else {
        tSampleFormat = AudioFormat.ENCODING_PCM_16BIT;
    }
    audioMinBufSizeLocal = AudioTrack.getMinBufferSize(mMusicSampleRate, tChannelConfig, tSampleFormat);
    // audioMinBufSizeLocal = PCMPlayerUtils.MEDIA_AUDIO_TRACK_BUFFER_SIZE;
    LogUtil.d(TAG, "audioMinBufSizeLocal= " + audioMinBufSizeLocal);
    mPreMediaSampleRate = mMusicSampleRate;
    mPreMediaChannelConfig = tChannelConfig;
    mPreMediaFormate = tSampleFormat;
    mPreMinBuffSize = audioMinBufSizeLocal;
    try {
        mMusicAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, mMusicSampleRate, tChannelConfig, tSampleFormat, audioMinBufSizeLocal, AudioTrack.MODE_STREAM);
    } catch (IllegalArgumentException e) {
        mMusicAudioTrack = null;
        informMusicPause();
        e.printStackTrace();
    }
    if (mMusicAudioTrack != null && mMusicAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
        try {
            mMusicAudioTrack.play();
        } catch (IllegalStateException e) {
            LogUtil.e(FTAG, "init media Audio track failed!");
            mMusicAudioTrack = null;
            informMusicPause();
            e.printStackTrace();
        }
    }
}

19 Source : AudioTrackManagerDualNormal.java
with Apache License 2.0
from ApolloAuto

@Override
public void initMusicAudioTrack(int sampleRate, int channelConfig, int sampleFormat) {
    int tChannelConfig;
    int tSampleFormat;
    int audioMinBufSizeLocal;
    // request Audio Focus
    if (getMusicAudioTrackFocus() == 0) {
        setMediaAudioFocusStatus(true);
    } else {
        setMediaAudioFocusStatus(false);
    }
    mMusicSampleRate = sampleRate;
    mMusicChannelConfig = channelConfig;
    mMusicSampleFormat = sampleFormat;
    releaseMusicAudioTrack();
    // avoid crush
    if (mMusicSampleRate <= 0) {
        mMusicSampleRate = 44100;
    }
    if (mMusicChannelConfig == 2) {
        tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
    } else if (mMusicChannelConfig == 1) {
        tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
    } else {
        tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
    }
    if (sampleFormat == 8) {
        tSampleFormat = AudioFormat.ENCODING_PCM_8BIT;
    } else {
        tSampleFormat = AudioFormat.ENCODING_PCM_16BIT;
    }
    audioMinBufSizeLocal = AudioTrack.getMinBufferSize(mMusicSampleRate, tChannelConfig, tSampleFormat);
    LogUtil.d(TAG, "audioMinBufSizeLocal= " + audioMinBufSizeLocal);
    mPreMediaSampleRate = mMusicSampleRate;
    mPreMediaChannelConfig = tChannelConfig;
    mPreMediaFormate = tSampleFormat;
    mPreMinBuffSize = audioMinBufSizeLocal;
    try {
        mMusicAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, mMusicSampleRate, tChannelConfig, tSampleFormat, audioMinBufSizeLocal, AudioTrack.MODE_STREAM);
    } catch (IllegalArgumentException e) {
        mMusicAudioTrack = null;
        informMusicPause();
        e.printStackTrace();
    }
    if (mMusicAudioTrack != null && mMusicAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
        try {
            mMusicAudioTrack.play();
        } catch (IllegalStateException e) {
            LogUtil.e(FTAG, "media audio track init failed!");
            mMusicAudioTrack = null;
            informMusicPause();
            e.printStackTrace();
        }
    }
}

19 Source : AudioTrackManagerDualNormal.java
with Apache License 2.0
from ApolloAuto

@Override
public void initTTSAudioTrack(int ttsType, int sampleRate, int channelConfig, int sampleFormat) {
    int tChannelConfig;
    int tSampleFormat;
    int audioMinBufSizeLocal;
    // request AudioFocus for TTS
    if (getTTSAudioTrackFocus(ttsType) == 0) {
        setTTSAudioFocusStatus(true);
    } else {
        setTTSAudioFocusStatus(false);
    }
    if (mTTSSampleRate != sampleRate || mTTSChannelConfig != channelConfig || mTTSSampleFormat != sampleFormat || mTTSAudioTrack == null) {
        mTTSSampleRate = sampleRate;
        mTTSChannelConfig = channelConfig;
        mTTSSampleFormat = sampleFormat;
        releaseTTSAudioTrack();
        // avoid crush
        if (mTTSSampleRate <= 0) {
            mTTSSampleRate = 16000;
        }
        if (mTTSChannelConfig == 2) {
            tChannelConfig = AudioFormat.CHANNEL_OUT_STEREO;
        } else if (mTTSChannelConfig == 1) {
            tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
        } else {
            tChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
        }
        if (sampleFormat == 8) {
            tSampleFormat = AudioFormat.ENCODING_PCM_8BIT;
        } else {
            tSampleFormat = AudioFormat.ENCODING_PCM_16BIT;
        }
        audioMinBufSizeLocal = AudioTrack.getMinBufferSize(mTTSSampleRate, tChannelConfig, tSampleFormat);
        LogUtil.d(TAG, "audioMinBufSizeLocal= " + audioMinBufSizeLocal);
        try {
            int ttsAudioTrackType = VehicleFactoryAdapter.getInstance().getTTSAudioTrackStreamType();
            mTTSAudioTrack = new AudioTrack(ttsAudioTrackType, mTTSSampleRate, tChannelConfig, tSampleFormat, audioMinBufSizeLocal, AudioTrack.MODE_STREAM);
        } catch (IllegalArgumentException e) {
            mTTSAudioTrack = null;
            e.printStackTrace();
        }
        if (mTTSAudioTrack != null) {
            try {
                mTTSAudioTrack.play();
            } catch (IllegalStateException e) {
                mTTSAudioTrack = null;
                LogUtil.e(FTAG, "tts audio track init failed!");
                e.printStackTrace();
            }
        }
    }
}

19 Source : AudioTrackManagerDualNormal.java
with Apache License 2.0
from ApolloAuto

@Override
public void resumeMusicAudioTrack() {
    // some times, initMusicAudioTrack() maybe fail
    if (mMusicAudioTrack == null) {
        reInitAudioTrack();
    }
    if ((mMusicAudioTrack != null) && (mMusicAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)) {
        try {
            mMusicAudioTrack.play();
        } catch (IllegalStateException e) {
            LogUtil.e(FTAG, "media resume failed!");
            informMusicPause();
            e.printStackTrace();
        }
    }
    if (getMusicAudioTrackFocus() == 0) {
        setMediaAudioFocusStatus(true);
    } else {
        setMediaAudioFocusStatus(false);
    }
}

19 Source : AudioStreamer.java
with Apache License 2.0
from AnywhereSoftware

/**
 * Starts playing. You should call Write to write the PCM data while playing is in progress.
 */
public void StartPlaying() {
    StopPlaying();
    player = new Player();
    track.play();
    playThread = new Thread(player);
    playThread.setDaemon(true);
    playThread.start();
}

19 Source : SimpleAudioOutput.java
with Apache License 2.0
from android

/**
 * Create an audio track then call play().
 *
 * @param frameRate
 */
public void start(int frameRate) {
    stop();
    mFrameRate = frameRate;
    mAudioTrack = createAudioTrack(frameRate);
    // AudioTrack will wait until it has enough data before starting.
    mAudioTrack.play();
}

18 Source : BeatSettingActivity.java
with Apache License 2.0
from YeDaxia

@OnClick(R.id.btn_play_beat)
void onPlayClick(View v) {
    if (playStatus == STATUS_PLAY_PREPARE) {
        stopPlay = false;
        audioTrack.play();
        // 预写一些填缓冲区
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        beatPlayHandler.sendEmptyMessage(R.integer.PLAY_BEAT);
        playStatus = STATUS_PLAYING;
    } else if (playStatus == STATUS_PLAYING) {
        stopPlay = true;
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        audioTrack.stop();
        playStatus = STATUS_PLAY_PREPARE;
    }
}

18 Source : AdjustRecordActivity.java
with Apache License 2.0
from YeDaxia

@OnClick(R.id.btn_play_beat)
void onStartPlayBeat(View v) {
    if (playStatus == STATUS_PLAY_PREPARE) {
        stopPlay = false;
        recordBarrier.reset();
        audioTrack.play();
        audioRecord.startRecording();
        // 预写一些填缓冲区
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        beatPlayHandler.sendEmptyMessage(R.integer.PLAY_BEAT);
        isFirstRecordWrite = true;
        isFirstPlayWrite = true;
        playStatus = STATUS_PLAYING;
        new AdjustThread().start();
    } else if (playStatus == STATUS_PLAYING) {
        stopPlay = true;
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        audioTrack.stop();
        audioRecord.stop();
        playStatus = STATUS_PLAY_PREPARE;
    }
}

18 Source : AudioRecordSyncTests.java
with Apache License 2.0
from YeDaxia

@Test
public void testPlay() {
    // 2秒的数据
    byte[] playCostBytes = new byte[playBytesLen];
    audioTrack.play();
    final long startWriteTime = System.currentTimeMillis();
    // 88200
    audioTrack.setNotificationMarkerPosition(playCostBytes.length / 2);
    audioTrack.setPlaybackPositionUpdateListener(new AudioTrack.OnPlaybackPositionUpdateListener() {

        @Override
        public void onMarkerReached(AudioTrack track) {
            Log.i(TAG, "play thread cost time : " + (System.currentTimeMillis() - startWriteTime));
        }

        @Override
        public void onPeriodicNotification(AudioTrack track) {
        }
    });
    audioTrack.write(playCostBytes, 0, playCostBytes.length);
    sleep(3000);
    Log.i(TAG, "onPeriodicNotification getPlaybackHeadPosition: " + audioTrack.getPlaybackHeadPosition());
    audioTrack.release();
}

18 Source : Tone.java
with Apache License 2.0
from tharvey

public boolean doFunction(String p1, int freqHz, int durationMs) {
    Log.i(TAG, "Tone: " + freqHz + "Hz " + durationMs + "ms");
    AudioTrack tone = generateTone(freqHz, durationMs);
    tone.setPlaybackPositionUpdateListener(new AudioTrack.OnPlaybackPositionUpdateListener() {

        @Override
        public void onPeriodicNotification(AudioTrack track) {
        }

        @Override
        public void onMarkerReached(AudioTrack track) {
            mPlaying = false;
            track.release();
        }
    });
    mPlaying = true;
    tone.play();
    return true;
}

18 Source : AudioPlayer.java
with Apache License 2.0
from StylingAndroid

@Override
public void startPlaying() {
    if (isPlaying()) {
        audioTrack.stop();
    }
    PlaybackParams playbackParams = audioTrack.getPlaybackParams();
    playbackParams.setPitch(speed);
    audioTrack.setPlaybackParams(playbackParams);
    audioTrack.setPlaybackPositionUpdateListener(positionListener);
    audioTrack.play();
    AudioPlayerTask playerTask = new AudioPlayerTask(audioTrack, file);
    playerThread = new Thread(playerTask);
    playerThread.start();
}

18 Source : SoundModule.java
with GNU General Public License v3.0
from skewyapp

public void playTestTone() {
    audioTrackTestTone.write(testTone, 0, testTone.length);
    audioTrackTestTone.play();
}

18 Source : DecodersTest.java
with Apache License 2.0
from ricohapi

public void audioDecoderTest(String filePath) throws IOException {
    AudioDecoder audioDecoderThread = new AudioDecoder(this, this);
    audioDecoderThread.initExtractor(filePath);
    audioDecoderThread.prepareAudio();
    int buffsize = AudioTrack.getMinBufferSize(audioDecoderThread.getSampleRate(), AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, audioDecoderThread.getSampleRate(), AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, buffsize, AudioTrack.MODE_STREAM);
    audioTrack.play();
    audioDecoderThread.start();
}

18 Source : Sender.java
with GNU General Public License v3.0
from raytheonbbn

@Override
protected Void doInBackground(String... params) {
    final int chanFormat = AudioFormat.CHANNEL_OUT_MONO;
    final int encoding = AudioFormat.ENCODING_PCM_16BIT;
    final int mode = AudioTrack.MODE_STATIC;
    final int bufSize = AudioTrack.getMinBufferSize(sampleRate, chanFormat, encoding);
    OutputBuffer buf = new OutputBuffer();
    final byte[] data = params[0].getBytes();
    Log.i(TAG, "Sending " + data.length + " bytes");
    Log.i(TAG, "Buffer size: " + bufSize);
    try {
        Main.send(new ByteArrayInputStream(data), buf);
    } catch (IOException e) {
        Log.e(TAG, "sending data failed", e);
        return null;
    }
    short[] samples = buf.samples();
    Log.i(TAG, "Effective buffer size in bytes: " + (Math.max(samples.length, bufSize) * 2));
    AudioTrack dst = new AudioTrack(streamType, sampleRate, chanFormat, encoding, Math.max(samples.length, bufSize) * 2, mode);
    int n = dst.write(samples, 0, samples.length);
    double duration = ((double) n) / sampleRate;
    Log.d(TAG, String.format("playing %d samples (%f seconds)", n, duration));
    dst.play();
    try {
        final double dt = 0.1;
        for (double t = 0; t < duration; t += dt) {
            publishProgress(t / duration);
            Thread.sleep((long) (dt * 1000));
        }
    } catch (InterruptedException e) {
    // nothing to do
    } finally {
        publishProgress(1.0);
    }
    dst.stop();
    dst.release();
    modemCotUtility.startListener();
    return null;
}

18 Source : AudioPlayPCM.java
with Apache License 2.0
from pop1234o

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void play(File file, int recorderSamplerate) throws IOException {
    if (!file.exists()) {
        Log.i("test", "play: 不存在");
        return;
    }
    FileInputStream inputStream = new FileInputStream(file);
    // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    // new AudioTrack.Builder().
    int bufferSize = AudioTrack.getMinBufferSize(recorderSamplerate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
    // 1296
    Log.i("test", "play: size " + bufferSize);
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, recorderSamplerate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
    // java.lang.IllegalStateException: play() called on uninitialized AudioTrack.
    // 如果是 MODE_STATIC模式,必须先调用write将数据全部写入,才能调用play播放
    audioTrack.play();
    byte[] bytes = new byte[2048];
    int length = 0;
    while ((length = inputStream.read(bytes)) != -1) {
        Log.i("test", "play: 写入" + length);
        // 写入到播放流中,系统自动将pcm数据转化为数字信号,然后是模拟信号
        audioTrack.write(bytes, 0, length);
    }
    audioTrack.stop();
    audioTrack.release();
    Log.i("test", "play: 播放结束");
    audioTrack = null;
    inputStream.close();
}

18 Source : AudioUtil.java
with Apache License 2.0
from pop1234o

/**
 * @param file
 * @param recorderSamplerate 16000
 * @throws IOException
 */
// @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void play(File file, int recorderSamplerate) throws IOException {
    if (!file.exists()) {
        Log.i("test", "play: 不存在");
        return;
    }
    FileInputStream inputStream = new FileInputStream(file);
    // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    // new AudioTrack.Builder().
    int bufferSize = AudioTrack.getMinBufferSize(recorderSamplerate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
    // 1296
    Log.i("test", "play: size " + bufferSize);
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, recorderSamplerate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
    // java.lang.IllegalStateException: play() called on uninitialized AudioTrack.
    // 如果是 MODE_STATIC模式,必须先调用write将数据全部写入,才能调用play播放
    audioTrack.play();
    byte[] bytes = new byte[2048];
    int length = 0;
    while ((length = inputStream.read(bytes)) != -1) {
        // Log.i("test", "play: 写入" + length);
        // 写入到播放流中,系统自动将pcm数据转化为数字信号,然后是模拟信号
        audioTrack.write(bytes, 0, length);
    }
    audioTrack.stop();
    audioTrack.release();
    Log.i("test", "play: 播放结束");
    audioTrack = null;
    inputStream.close();
}

18 Source : FromFileBase.java
with Apache License 2.0
from pedroSG94

public void playAudioDevice() {
    if (audioEnabled) {
        if (isAudioDeviceEnabled()) {
            audioTrackPlayer.stop();
        }
        int channel = audioDecoder.isStereo() ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO;
        int buffSize = AudioTrack.getMinBufferSize(audioDecoder.getSampleRate(), channel, AudioFormat.ENCODING_PCM_16BIT);
        audioTrackPlayer = new AudioTrack(AudioManager.STREAM_MUSIC, audioDecoder.getSampleRate(), channel, AudioFormat.ENCODING_PCM_16BIT, buffSize, AudioTrack.MODE_STREAM);
        audioTrackPlayer.play();
    }
}

18 Source : TonePlayer.java
with GNU Lesser General Public License v3.0
from m-abboud

protected void playSound(int sampleRate, byte[] soundData) {
    try {
        int bufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        // if buffer-size changing or no previous obj then allocate:
        if (bufferSize != audTrackBufferSize || audioTrack == null) {
            if (audioTrack != null) {
                // release previous object
                audioTrack.pause();
                audioTrack.flush();
                audioTrack.release();
            }
            // allocate new object:
            audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
            audTrackBufferSize = bufferSize;
        }
        float gain = (float) (volume / 100.0);
        // noinspection deprecation
        audioTrack.setStereoVolume(gain, gain);
        audioTrack.play();
        audioTrack.write(soundData, 0, soundData.length);
    } catch (Exception e) {
        Log.e("tone player", e.toString(), e);
    }
}

18 Source : SamplePlayer.java
with GNU General Public License v3.0
from KaustubhPatange

public void start() {
    if (isPlaying()) {
        return;
    }
    mKeepPlaying = true;
    mAudioTrack.flush();
    mAudioTrack.play();
    // Setting thread feeding the audio samples to the audio hardware.
    // (replacedumes mChannels = 1 or 2).
    mPlayThread = new Thread() {

        public void run() {
            int position = mPlaybackStart * mChannels;
            mSamples.position(position);
            int limit = mNumSamples * mChannels;
            while (mSamples.position() < limit && mKeepPlaying) {
                int numSamplesLeft = limit - mSamples.position();
                if (numSamplesLeft >= mBuffer.length) {
                    mSamples.get(mBuffer);
                } else {
                    for (int i = numSamplesLeft; i < mBuffer.length; i++) {
                        mBuffer[i] = 0;
                    }
                    mSamples.get(mBuffer, 0, numSamplesLeft);
                }
                // TODO(nfaralli): use the write method that takes a ByteBuffer as argument.
                mAudioTrack.write(mBuffer, 0, mBuffer.length);
            }
        }
    };
    mPlayThread.start();
}

18 Source : AudioJack.java
with Apache License 2.0
from fossasia

private boolean configure() {
    if ("input".equals(io)) {
        /* Initialize audioRecord */
        minRecorderBufferSize = AudioRecord.getMinBufferSize(SAMPLING_RATE, RECORDING_CHANNEL, RECORDER_AUDIO_ENCODING);
        if (minRecorderBufferSize == AudioRecord.ERROR || minRecorderBufferSize == AudioRecord.ERROR_BAD_VALUE) {
            minRecorderBufferSize = SAMPLING_RATE * 2;
        }
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLING_RATE, RECORDING_CHANNEL, RECORDER_AUDIO_ENCODING, minRecorderBufferSize);
        if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
            Log.e(TAG, "Audio Record can't be initialized");
            return false;
        }
        audioRecord.startRecording();
    } else {
        /* Initialize audioTrack */
        minTrackBufferSize = AudioTrack.getMinBufferSize(SAMPLING_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        if (minTrackBufferSize == AudioTrack.ERROR || minTrackBufferSize == AudioTrack.ERROR_BAD_VALUE) {
            minTrackBufferSize = SAMPLING_RATE * 2;
        }
        // Using STREAM_MUSIC. So to change amplitude stream music needs to be changed
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLING_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minTrackBufferSize, AudioTrack.MODE_STREAM);
        if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
            Log.e(TAG, "AudioTrack can't be initialized");
            return false;
        }
        audioTrack.play();
    }
    return true;
}

18 Source : AudioTrackManagerSingle.java
with Apache License 2.0
from ApolloAuto

public void resumeAudioTrack() {
    if ((mAudioTrack != null) && (mAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)) {
        try {
            mAudioTrack.pause();
            mAudioTrack.flush();
            mAudioTrack.play();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
    // get audio track focus
    getAudioTrackFocus();
}

17 Source : WorkspaceActivity.java
with Apache License 2.0
from YeDaxia

private void startPlay() {
    if (ListUtils.isNotEmpty(trackHolderList)) {
        int newChannelCount = recordStatus == STATUS_RECORD_RECORDING ? trackHolderList.size() : trackHolderList.size() + 1;
        if (musicAudioTrack == null) {
            musicAudioTrack = AudioUtils.createTrack(newChannelCount);
        } else if (musicAudioTrack.getChannelCount() != newChannelCount) {
            musicAudioTrack.release();
            musicAudioTrack = AudioUtils.createTrack(newChannelCount);
        }
        playStatus = STATUS_PLAYING;
        btnPlay.setIcon(ResUtils.getDrawable(R.drawable.ic_pause));
        stopPlay = false;
        initTrackInputs();
        musicAudioTrack.play();
        new PlayThread().start();
    }
}

17 Source : StudioActivity.java
with GNU General Public License v2.0
from theo-jedi

@SuppressLint("WrongConstant")
private void startPlay() {
    if (ArrayUtils.isNotEmpty(trackHolderList)) {
        int newChannelCount = recordStatus == STATUS_RECORD_RECORDING ? trackHolderList.size() : trackHolderList.size() + 1;
        if (musicAudioTrack == null) {
            musicAudioTrack = AudioUtils.createTrack(newChannelCount);
        } else if (musicAudioTrack.getChannelCount() != newChannelCount) {
            musicAudioTrack.release();
            musicAudioTrack = AudioUtils.createTrack(newChannelCount);
        }
        playStatus = STATUS_PLAYING;
        mPlayButton.setImageResource(R.drawable.av_pause_24dp);
        stopPlay = false;
        initTrackInputs();
        musicAudioTrack.play();
        new PlayThread().start();
    }
}

17 Source : AdjustRecordActivity.java
with GNU General Public License v2.0
from theo-jedi

void onStartPlayBeat(View v) {
    if (playStatus == STATUS_PLAY_PREPARE) {
        mResultTextView.setVisibility(View.INVISIBLE);
        stopPlay = false;
        recordBarrier.reset();
        audioTrack.play();
        audioRecord.startRecording();
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        beatPlayHandler.sendEmptyMessage(R.integer.PLAY_BEAT);
        isFirstRecordWrite = true;
        isFirstPlayWrite = true;
        playStatus = STATUS_PLAYING;
        new AdjustThread().start();
    } else if (playStatus == STATUS_PLAYING) {
        stopPlay = true;
        beatPlayHandler.removeMessages(R.integer.PLAY_BEAT);
        audioTrack.stop();
        audioRecord.stop();
        playStatus = STATUS_PLAY_PREPARE;
    }
    updatePlayImage();
}

17 Source : AudioRender.java
with MIT License
from qiniu

public int openTrack(int sampleRate, int channelCount) {
    if (mAudioTrack != null)
        closeTrack();
    int nChannelConfig = (channelCount == 1) ? AudioFormat.CHANNEL_CONFIGURATION_MONO : AudioFormat.CHANNEL_CONFIGURATION_STEREO;
    int nMinBufSize = AudioTrack.getMinBufferSize(sampleRate, nChannelConfig, AudioFormat.ENCODING_PCM_16BIT);
    if (nMinBufSize == AudioTrack.ERROR_BAD_VALUE || nMinBufSize == AudioTrack.ERROR)
        return -1;
    nMinBufSize = nMinBufSize * 2;
    if (nMinBufSize < 8192)
        nMinBufSize = 8192;
    Log.v(TAG, "Audio track, nMinBufSize  " + nMinBufSize);
    mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, nChannelConfig, AudioFormat.ENCODING_PCM_16BIT, nMinBufSize, AudioTrack.MODE_STREAM);
    int param = nMinBufSize * 1000 / (sampleRate * channelCount * 2);
    // param = param + mOffset;
    if (mPlayer != null) {
        if (mOffset > 0)
            param = param | 0X80000000;
        mPlayer.SetParam(mPlayer.QCPLAY_PID_Clock_OffTime, param, null);
    }
    mAudioTrack.play();
    return 0;
}

17 Source : FromFileBase.java
with Apache License 2.0
from pedroSG94

private void startEncoders() {
    if (videoEnabled)
        videoEncoder.start();
    if (audioTrackPlayer != null)
        audioTrackPlayer.play();
    if (audioEnabled)
        audioEncoder.start();
    if (videoEnabled)
        prepareGlView();
    if (videoEnabled)
        videoDecoder.start();
    if (audioEnabled)
        audioDecoder.start();
}

17 Source : WebRtcAudioTrack.java
with MIT License
from pcgpcgpcg

private boolean startPlayout() {
    threadChecker.checkIsOnValidThread();
    Logging.d(TAG, "startPlayout");
    replacedertTrue(audioTrack != null);
    replacedertTrue(audioThread == null);
    // Starts playing an audio track.
    try {
        audioTrack.play();
    } catch (IllegalStateException e) {
        reportWebRtcAudioTrackStartError(AudioTrackStartErrorCode.AUDIO_TRACK_START_EXCEPTION, "AudioTrack.play failed: " + e.getMessage());
        releaseAudioResources();
        return false;
    }
    if (audioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
        reportWebRtcAudioTrackStartError(AudioTrackStartErrorCode.AUDIO_TRACK_START_STATE_MISMATCH, "AudioTrack.play failed - incorrect state :" + audioTrack.getPlayState());
        releaseAudioResources();
        return false;
    }
    // Create and start new high-priority thread which calls AudioTrack.write()
    // and where we also call the native nativeGetPlayoutData() callback to
    // request decoded audio from WebRTC.
    audioThread = new AudioTrackThread("AudioTrackJavaThread");
    audioThread.start();
    return true;
}

17 Source : BlockingAudioTrack.java
with Apache License 2.0
from lulululbj

private static int writeToAudioTrack(AudioTrack audioTrack, byte[] bytes) {
    if (audioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
        if (DBG)
            Log.d(TAG, "AudioTrack not playing, restarting : " + audioTrack.hashCode());
        audioTrack.play();
    }
    int count = 0;
    while (count < bytes.length) {
        // Note that we don't take bufferCopy.mOffset into account because
        // it is guaranteed to be 0.
        int written = audioTrack.write(bytes, count, bytes.length);
        if (written <= 0) {
            break;
        }
        count += written;
    }
    return count;
}

17 Source : AudioTrackPlayerImpl.java
with Apache License 2.0
from dueros

private AudioTrack createAudioTrack(int sampleRate) {
    int encoding = AudioFormat.ENCODING_PCM_16BIT;
    // 得到一个满足最小要求的缓冲区的大小
    int minBufferSize = getMinBufferSize(sampleRate, mChannelConfig, encoding);
    Log.d(TAG, "Decoder-AudioTrack-minBufferSize=" + minBufferSize);
    AudioTrack audioTrack = new AudioTrack(mStreamType, sampleRate, mChannelConfig, encoding, minBufferSize, AudioTrack.MODE_STREAM);
    audioTrack.play();
    return audioTrack;
}

See More Examples