gpt4 book ai didi

android - AudioTrack Android 播放原始文件夹中的声音

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:22:18 24 4
gpt4 key购买 nike

是否可以使用资源文件夹 raw 中的 AudioTrack 播放 wav 文件?它尝试了很多方法来引用我的 Android 项目中的原始文件,但我遇到了很多异常。

这就是我现在拥有的,但是当我按下按钮时,没有声音播放。

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();
}
}

最佳答案

你的代码一切都很好,你只需要改变

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

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

关于android - AudioTrack Android 播放原始文件夹中的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com