public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
playfilesound();
}
private void playfilesound() throws IOException
{
int count = 512 * 1024; // 512 kb
//Reading the file..
byte[] byteData = null;
File file = null;
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+"recordsound"); //filePath
byteData = new byte[(int)count];
FileInputStream in = null;
try {
in = new FileInputStream( file );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int bytesread = 0, ret = 0;
int size = (int) file.length();
audioTrack.play();
while (bytesread < size) { // Write the byte array to the track
ret = in.read( byteData,0, count); //ret =size in bytes
if (ret != -1) {
audioTrack.write(byteData,0, ret);
bytesread += ret; } //ret
else break;
} //while
in.close();
audioTrack.stop(); audioTrack.release();
}
我使用调试器单步执行代码并将鼠标悬停在 audioTrack 上方,它已分配并初始化。该文件也存在。
但是当它点击 audioTrack.play() 时,它会抛出一个错误,说它的非法状态异常,未使用的 AudioTrack。
我附上了包含录音文件部分的项目。 http://www.mediafire.com/?6i2r3whg7e7rs79