2013-02-28 170 views
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,它的分配和inited。該文件也存在。Android AudioTrack錯誤:未初始化的AudioTrack

但是,當它擊中audioTrack.play()時,它會拋出一個錯誤,指出其非法狀態異常,未使用的AudioTrack。

我附上了包含錄音文件部分的項目。 http://www.mediafire.com/?6i2r3whg7e7rs79

回答

1

看起來像你在寫作之前稱爲玩遊戲!試試這個...

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 
1

使用通道的配置被中斷,在AudioFormat.CHANNEL_CONFIGURATION_MONO的地方使用AudioFormat.CHANNEL_IN_MONO錄製並AudioFormat.CHANNEL_OUT_MONO玩...

+1

請SO使用英語和英語只在這裏。 – 2017-02-02 00:25:59

+0

Por支持,utilice elinglésysóloelinglésaquíen SO。 – NobodyNada 2017-02-02 00:26:41