Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

AndroidでAudioTrackを使ってPCMファイルを鳴らす。

More than 5 years have passed since last update.

assetsフォルダに置いた16Bit StereoのリニアPCMファイルを鳴らすコード的なもの。

class PlayThread extends Thread {
    byte[] pcmData;
    AudioTrack audioTrack;
    float maxVolume ;
    float minVolume;
    PlayThread(String filename) {
        setPcmData(filename);
        makeAudioTrack();
        maxVolume = AudioTrack.getMaxVolume();
        minVolume = AudioTrack.getMinVolume();
    }
    public void run() {
        if (audioTrack != null) {
            int result= audioTrack.setLoopPoints(0, pcmData.length/4, -1);
            if (result != AudioTrack.SUCCESS) {
                System.out.println("result="+result+"pcmData.length="+ pcmData.length);
            }
            audioTrack.write(pcmData, 0, pcmData.length);
            audioTrack.play();
        }

    }
    void makeAudioTrack() {

        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
                AudioFormat.ENCODING_PCM_16BIT, pcmData.length,
                AudioTrack.MODE_STATIC);
    }

    void playStop() {
        if (audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
            audioTrack.stop();
            audioTrack.release();
        }
    }
    void setStereoVolume(int left,int right) {
        float leftF = minVolume+(maxVolume-minVolume)*left/100;
        float rightF = minVolume+(maxVolume-minVolume)*right/100;
        audioTrack.setStereoVolume(leftF, rightF);
    }
    void setPcmData(String s) {
        AssetManager as = getResources().getAssets();
        AssetFileDescriptor afd = null;

        try {
            afd = as.openFd (s);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (afd != null) {
            pcmData = new byte[(int)afd.getLength()];
            InputStream is = null;
            try {
                is = afd.createInputStream();
                is.read(pcmData);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                IOUtils.closeQuietly(is);
            }
        }else {

            finish();
        }
    }
}

}

farvel
CとかScalaとかGroovyとかClojureとか好物です。長いコードの著作権はCC BYで
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away