AudioTrack Android playing sounds from raw folder

妖精的绣舞 提交于 2019-12-18 04:55:17

问题


Is it possible to play wav files with AudioTrack from the resources folder raw? It tried many ways to reference the raw files in my Android project, but I got a lot of exceptions.

This is what I have now, but when I press the button, no sound plays.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button buttonPlayAudioTrack = (Button) findViewById(R.id.buttonPlayAudioTrack);
    buttonPlayAudioTrack.setOnClickListener(this);

    int minBufferSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, 
                        AudioFormat.ENCODING_PCM_16BIT);

    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, 
                     AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM); 
}
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId() == R.id.buttonPlayAudioTrack) 
        playSound();
}

private void playSound() {
    audioTrack.play();
    int i = 0;
    int bufferSize = 512;
    byte [] buffer = new byte[bufferSize];
    InputStream inputStream = getResources().openRawResource(R.raw.piano12);
    try {
        while((i = inputStream.read()) != -1)
            audioTrack.write(buffer, 0, i);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        inputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

回答1:


Everything is fine with your code, You just need to change

while((i = inputStream.read()) != -1) 

to

while((i = inputStream.read(buffer)) != -1)


来源:https://stackoverflow.com/questions/12263671/audiotrack-android-playing-sounds-from-raw-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!