Using AudioTrack in Android to play a WAV file

后端 未结 7 965
别跟我提以往
别跟我提以往 2020-12-01 05:50

I\'m working with Android, trying to make my AudioTrack application play a Windows .wav file (Tada.wav). Frankly, it shouldn\'t be this hard, but I\'m hearing a lot of stra

7条回答
  •  时光取名叫无心
    2020-12-01 05:54

    I found a lot of long answers to this question. My final solution, which given all the cutting and pasting is hardly mine, comes down to:

    public boolean play() {
    
        int i = 0;
        byte[] music = null;
        InputStream is = mContext.getResources().openRawResource(R.raw.noise);
    
        at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
            AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
            minBufferSize, AudioTrack.MODE_STREAM);
    
        try{
            music = new byte[512];
            at.play();
    
            while((i = is.read(music)) != -1)
                at.write(music, 0, i);
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        at.stop();
        at.release();
        return STOPPED;
    }
    

    STOPPED is just a "true" sent back as a signal to reset the pause/play button. And in the class initializer:

    public Mp3Track(Context context) {
        mContext = context;
        minBufferSize = AudioTrack.getMinBufferSize(44100,
            AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
    }
    

    Context is just "this" from the calling activity. You can use a FileInputStream on the sdcard, etc. My files are in res/raw

提交回复
热议问题