我正在使用AudioTrack库来播放通过wifi流式传输的pcm样本。问题是在 Lenovo K900(4.1.2)上播放时播放非常不稳定,而在 OnePlusOne(Marshmallow 6.0.1 cyanogen)手机上播放时则无缝播放。 为了排除流延迟,我首先将整个流加载到一个数组中,然后通过循环遍历预先填充的数组来播放音频。仍有事情根本没有改善。 现在 K900 正在运行 Android 4.1.2 而我使用的android sdk是用于 API23 ,我的意思是当我打开AudioTrack类的定义时打开 API23 的类文件。这会引起任何问题吗?
int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_8BIT);
if (bufferSize == AudioTrack.ERROR || bufferSize == AudioTrack.ERROR_BAD_VALUE) {
bufferSize = SAMPLE_RATE * 2;
}
int readBytes;
int bufSize=2123880;//size of the file being streamed
byte[] buffer=new byte[bufSize];
//bufferSize*=2;
DataInputStream in = new DataInputStream(socket.getInputStream());
readBytes=0;
while(true) {
try {
if(in.available()>0){
readBytes+=in.read(buffer, readBytes, in.available());
// audioTrack.write(buffer,0,readBytes);
}else{
break;
}
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
//audioTrack.release();
break;
} catch (IOException e) {
e.printStackTrace();
//audioTrack.release();
break;
}
}
in.close();
readBytes=0;
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_8BIT,
bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
while(readBytes<bufSize){
readBytes+=audioTrack.write(buffer,readBytes,bufferSize);
}
audioTrack.release();
我测试了不同采样率的样本,范围从 19250hz 到 44100hz 。对于所有情况 K900 强文字播放不稳定而Oneplus播放顺畅。我不认为 K900 不足以完成这项简单的工作。 请帮助。
修改 这是我打算使用的代码:
try {
//dataInputStream = new DataInputStream(socket.getInputStream());
//response = dataInputStream.readUTF();
int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_8BIT);
if (bufferSize == AudioTrack.ERROR || bufferSize == AudioTrack.ERROR_BAD_VALUE) {
bufferSize = SAMPLE_RATE * 2;
}
int readBytes;
byte[] buffer = new byte[bufferSize];
bufferSize = bufferSize * 2;
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_8BIT,
bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
DataInputStream in = new DataInputStream(socket.getInputStream());
while (true) {
try {
if (in.available() > 0) {
readBytes = in.read(buffer, 0, buffer.length);
audioTrack.write(buffer, 0, readBytes);
}
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
audioTrack.release();
in.close();
socket.close();
break;
} catch (IOException e) {
e.printStackTrace();
audioTrack.release();
in.close();
socket.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
谢谢, Debojit