0
  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

4

3 回答 3

2

您使用的频道的配置已停止,代替AudioFormat.CHANNEL_CONFIGURATION_MONOUses AudioFormat.CHANNEL_IN_MONOTo record and AudioFormat.CHANNEL_OUT_MONOplay...

于 2017-02-02T00:24:17.520 回答
0

看起来你在写之前就打电话了!尝试这个 ...

int bytesread = 0, ret = 0;
int size = (int) file.length();
//audioTrack.play();  <---- play called prematurely



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; 
        audioTrack.play(); //<--- try calling it here!
    }  //ret
    else break; 

}   //while
于 2013-08-19T15:21:07.243 回答
0

您在这里遇到的问题不止一个:

  • 已停产的频道部分尚未得到答复。
  • 不要在 UI 线程上播放音频!

还请格式化您的代码。

编辑:我还添加了

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);

使播放更柔和。然后您可以再次将其设置为默认值:

android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
于 2020-03-23T01:30:09.900 回答