9

我需要同时运行两个 AudioTrack 实例。它们必须单独运行,因为我以不同的可变采样率播放它们。我发现如果我在同一个线程中运行它们,它们会“轮流”。我在各自的线程中运行它们,但音频结结巴巴。

关于让两个实例玩得很好的任何想法?如果没有,任何将两个短缓冲区混合为一个的提示,即使我想以不同的采样率播放它们。

4

1 回答 1

12

我一次播放了 4 个音轨,它们似乎播放得很好。在 HTC Desire 1.1ghz OC 上进行测试。不过,有时我的线程会出现故障。有时,如果四个人都在玩,当我尝试加入线程时,一个人不会停止。需要做更多的测试。这是我播放在给定路径记录的 wav 文件的类

    package com.ron.audio.functions;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class AudioPlayManager implements Runnable {

private File fileName;
private volatile boolean playing;

public AudioPlayManager() {
    super();
    setPlaying(false);
}

public void run(){
      // Get the length of the audio stored in the file (16 bit so 2 bytes per short)
      // and create a short array to store the recorded audio.
      int musicLength = (int)(fileName.length()/2);
      short[] music = new short[musicLength];

      try {
        // Create a DataInputStream to read the audio data back from the saved file.
        InputStream is = new FileInputStream(fileName);
        BufferedInputStream bis = new BufferedInputStream(is);
        DataInputStream dis = new DataInputStream(bis);

        // Read the file into the music array.
        int i = 0;
        while (dis.available() > 0) {
          music[i] = dis.readShort();
          i++;
        }

        // Close the input streams.
        dis.close();     

        // Create a new AudioTrack object using the same parameters as the AudioRecord
        // object used to create the file.
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 
                                                11025, 
                                               AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                               AudioFormat.ENCODING_PCM_16BIT, 
                                               musicLength, 
                                               AudioTrack.MODE_STREAM);
        // Start playback
        audioTrack.play();

        // Write the music buffer to the AudioTrack object
        while(playing){
            audioTrack.write(music, 0, musicLength);
        }

      }
      catch(Exception e){
          e.printStackTrace();
      }

}


public void setFileName(File fileName) {
    this.fileName = fileName;
}

public File getFileName() {
    return fileName;
}

public void setPlaying(boolean playing) {
    this.playing = playing;
}

public boolean isPlaying() {
    return playing;
}

}

于 2011-01-26T23:16:22.467 回答