I want to make an activity with a ListView that plays different sound effects when list item is clicked. I tested this feature with MediaPlayer and SoundPool and both work fine.
I implemented AudioTrack but when I click an item from the ListView, it only plays noise or crashes saying "Invalid audio buffer size."
Here's my code.
public class ATSoundAdapter extends ArrayAdapter {
private ArrayList<SoundData> mData;
private Context context;
private AudioTrack at;
public ATSoundAdapter(Context context, ArrayList<SoundData> mData) {
super(context, -1);
this.context = context;
this.mData = mData;
}
public class ViewHolder {
private TextView mSoundNameTv;
private LinearLayout container;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
holder.mSoundNameTv = (TextView) convertView.findViewById(R.id.sound_name_tv);
holder.container = (LinearLayout) convertView.findViewById(R.id.container);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final SoundData currentSound = mData.get(position);
if (currentSound != null) {
holder.mSoundNameTv.setText(currentSound.getSoundName());
holder.container.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playAudioTrack(currentSound.getSoundResource());
}
});
}
return convertView;
}
private void playAudioTrack(int resource) {
int i = 0;
InputStream inputStream = context.getResources().openRawResource(resource);
long bufferSize = context.getResources().openRawResourceFd(resource).getLength();
byte[] buffer = new byte[(int)bufferSize];
try {
int lengthOfAudioClip = inputStream.read(buffer, 0, buffer.length);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,
44100, AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
lengthOfAudioClip, AudioTrack.MODE_STATIC);
at.write(buffer, 0, lengthOfAudioClip);
inputStream.close();
at.play();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public int getCount() {
return mData.size();
}
}
I thought the byte array size was wrong... But when I checked it in logcat, it was exactly the size of the raw file. I'm new to android and have no idea how to use AudioTrack.
Thanks in advance.
you can change your code
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, lengthOfAudioClip, AudioTrack.MODE_STREAM);
or else you can check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With