1
回答
怎么使用audioTrack来播放短时的pcm音频?
注册华为云得mate10,2.9折抢先购!>>>   

在使用audioTrack类播放pcm音频有两个方式,一种是stream,另一种是static。

当音频较长时,一般大于minBufferSize(),先调用play(),再循环调用write()直到音频结束,这样播放基本正常。

当音频很短时,只有小到0.1s时,没有bufferSize()那么大,无论是使用stream还static,播放时成功率都不高,有时点播放几次都不成功,使用两个手机实验:

小米2s 4.1.1 成功率90%左右,播放1s以上的音频100%成功。

华为p6 4.4.2 成功率50%以内,播放1s以上的音频100%成功。

想问问为什么会这样,是和buffer有关吗?


public void recordPlay() {
		//dataFile=new File(dataDir, FILE_NAME1);
		if(!dataFile1.exists()){
			isRecordPlaying=false;
		}
		
		InputStream is = null;
		try {
			is = new FileInputStream(dataFile1);
		} catch (FileNotFoundException e) {
			Log.e("AR", "input stream failed");
			e.printStackTrace();
		}
		BufferedInputStream bis = new BufferedInputStream(is);
		
		/*int musicLength = (int) (dataFile1.length());
		byte[] music = new byte[musicLength];
		
		try {
			
                readResult = bis.read(music, 0, musicLength);
		} catch (IOException e1) {

			e1.printStackTrace();
		}*/
		
		
		
		
		minBufferSize=AudioTrack.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNELS_CONFIG_OUT, ENCODER_CONFIG);

//	    int length=(minBufferSize>musicLength) ? minBufferSize : musicLength;
	    int length= minBufferSize;

//        System.out.println("minBufferSize:"+minBufferSize + " | musicLenth:" + musicLength + " | length:" + length +"readResult:" + readResult);
	    AudioTrack audioTrack=new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE_IN_HZ, CHANNELS_CONFIG_OUT, ENCODER_CONFIG, length , AudioTrack.MODE_STREAM);

        /*byte writeInTrack[];
        if (length > musicLength)
        {
            writeInTrack = new byte[length];
            for (int i = 0; i < musicLength; ++i)
            {

                writeInTrack[i] = music [i];
            }
            for (int i = musicLength; i < length; ++i)
            {

                writeInTrack[i] = 0;
            }
        }else
        {
            writeInTrack = music;
        }
        //byte writeInTrack[] = music;
		audioTrack.write(writeInTrack, 0, musicLength);*/
	    audioTrack.play();
   

	    int readResult = 0;
        byte buffer[] = new byte[length];
	    isRecordPlaying=true;
	    while (isRecordPlaying) {
	    	try {
				readResult=bis.read(buffer, 0, length);
				System.out.println("result:"+readResult);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	    	if(readResult!=-1){
	    		audioTrack.write(buffer, 0, readResult);
//	    		System.out.println("write");
	    	}else {
				isRecordPlaying=false;

			}
	    	
		}

	  //close the file
    	try {
			bis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
	    audioTrack.stop();
	    audioTrack.release();
	    audioTrack=null;
//	    System.out.println("release");
	}





举报
石頭Ng
发帖于4年前 1回/2K+阅
顶部