所以我有一个按钮可以在按下时播放录音带,然后在第二次按下时停止录音带。当我单击按钮时,它退出应用程序。我不知道为什么。请帮忙!
public void Playbutton(View view) {
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
int shortSizeInBytes = Short.SIZE / Byte.SIZE;
int bufferSizeInBytes = (int) (file.length() / shortSizeInBytes);
short[] audioData = new short[bufferSizeInBytes];
try {
InputStream inputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);
int i = 0;
while (dataInputStream.available() > 0) {
audioData[i] = dataInputStream.readShort();
i++;
}
dataInputStream.close();
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
11025,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSizeInBytes,
AudioTrack.MODE_STREAM);
if (playbuttonstatus){
playBtn.setText(getString(R.string.stop));
audioTrack.play();
audioTrack.write(audioData, 0, bufferSizeInBytes);
playbuttonstatus = false;}
else{
playBtn.setText(getString(R.string.play));
playbuttonstatus = true;
audioTrack.pause();
audioTrack.flush();}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
在项目中使用此代码。我认为它会对你有所帮助:
Boolean audiopaused=true;
Button play.setOnclickListener(new Onclicklistener){
if (audiopaused){
audio.start();
}esle{
audio.stop();
}
}
答案 1 :(得分:0)
现在,无论playbuttonstatus
的状态如何,您始终都会运行相同的初始化。因此,在您首次在AudioTrack
的一个实例上开始播放并再次按下该按钮之后,您再创建另一个新AudioTrack
实例,并尝试停止它,尽管它还没有播放。这可能会导致IllegalStateException
。 (而且你也没能阻止原来的。)
您可以将audioTrack
作为playButton()
方法之外的类的成员变量:
private AudioTrack audioTrack;
然后您可以更改代码,以便启动和停止相同的AudioTrack
。
public void playButton(View view) {
if (playbuttonstatus){
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
int shortSizeInBytes = Short.SIZE / Byte.SIZE;
int bufferSizeInBytes = (int) (file.length() / shortSizeInBytes);
short[] audioData = new short[bufferSizeInBytes];
try {
InputStream inputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);
int i = 0;
while (dataInputStream.available() > 0) {
audioData[i] = dataInputStream.readShort();
i++;
}
dataInputStream.close();
audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
11025,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSizeInBytes,
AudioTrack.MODE_STREAM);
playBtn.setText(getString(R.string.stop));
audioTrack.play();
audioTrack.write(audioData, 0, bufferSizeInBytes);
playbuttonstatus = false;
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
playBtn.setText(getString(R.string.play));
playbuttonstatus = true;
audioTrack.pause();
audioTrack.flush();
}
}