Android AudioTrack播放.wav文件,只获得白噪声

use*_*zer 7 audio android bytearray inputstream pcm

当我使用以下代码播放文件时:

private void PlayAudioFileViaAudioTrack(int ResId) throws IOException {

    int intSize = android.media.AudioTrack.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);

    AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, intSize,
            AudioTrack.MODE_STREAM);

    int count = 256 * 1024; // 256 kb
    byte[] byteData = null;
    byteData = new byte[(int) count];
    InputStream in = null;
    AssetFileDescriptor fd = null;
    fd = mResources.openRawResourceFd(ResId);
    in = mResources.openRawResource(ResId);

    int bytesRead = 0, amount = 0;
    int size = (int) fd.getLength();
    at.play();
    while (bytesRead < size) {
        amount = in.read(byteData, 0, count);
        if (amount != -1) {
            at.write(byteData, 0, amount);
        }
    }
    in.close();
    at.stop();
    at.release();

}
Run Code Online (Sandbox Code Playgroud)

我听到的唯一的东西是静电,白噪声.我检查过我的.wav文件具有相同的属性(samplerate,bitrate).我对原始音频数据(PCM)不太了解,所以我想知道是否有人能看到我的代码有什么问题.

Man*_*nos 7

从您的代码中我可以看到您只是从wav文件中读取数据并将它们导入AudioTrack.Wav文件有一个小标题,你可以在这里看到https://ccrma.stanford.edu/courses/422/projects/WaveFormat/所以你必须跳过标题并将文件描述符指向实际音频数据的正确位置是.

此外,当您播放音频文件并处理字节操作时,您应该处理Endianess.看看这里在Android中使用AudioTrack播放WAV文件

在我的代码下面(一些检查和WAV标题跳过丢失)在Nexus One和Galaxy S中都可以使用频率为8000Hz和16位编码的wav文件.

public void playWav(){
    int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
    int bufferSize = 512;
    AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();

    int i = 0;
    byte[] s = new byte[bufferSize];
    try {
        FileInputStream fin = new FileInputStream(filepath + "/REFERENCE.wav");
        DataInputStream dis = new DataInputStream(fin);

        at.play();
        while((i = dis.read(s, 0, bufferSize)) > -1){
            at.write(s, 0, i);

        }
        at.stop();
        at.release();
        dis.close();
        fin.close();

    } catch (FileNotFoundException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    }       
}
Run Code Online (Sandbox Code Playgroud)