Android:将AudioTrack写入.wav文件 - 可能吗?

时间:2014-01-19 16:32:28

标签: android audio

所以我需要用ToneGenerator生成一些音调并将它们写入.wav文件。可以使用ToneGeneratorAudioTrack吗?

有没有办法直接在AudioTrack中访问音频帧,使用AudioOutput录制到文件或做其他事情?

2 个答案:

答案 0 :(得分:0)

ToneGenerator指定生成的音频数据写入的输出流类型。无法直接访问生成的音频数据。

当然,您可以录制播放的音调,例如通过内置麦克风。但那可能不是你想要的。

当使用适当的audioSource,sampleRateInHz,channelConfig,audioFormat和streamType设置时,您还可以使用AudioRecord在某些设备上以数字方式录制它们。

关于AudioTrack,由于您必须使用write()方法,因此您必须能够直接访问音频数据。

答案 1 :(得分:0)

这可能会对您有所帮助:

public class GenerateAndPlaySound extends Activity {
    private final int duration = 3; // seconds
    private final int sampleRate = 8000;
    private final int numSamples = duration * sampleRate;
    private final double sample[] = new double[numSamples];
    private final double freqOfTone = 440; // hz

    private final byte generatedSnd[] = new byte[2 * numSamples];

    Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Use a new tread as this can take a while
        final Thread thread = new Thread(new Runnable() {
            public void run() {
                genTone();
                handler.post(new Runnable() {

                    public void run() {
                        playSound();
                    }
                });
            }
        });
        thread.start();
    }

    void genTone(){
        // fill out the array
        for (int i = 0; i < numSamples; ++i) {
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
        }

        // convert to 16 bit pcm sound array
        // assumes the sample buffer is normalised.
        int idx = 0;
        for (final double dVal : sample) {
            // scale to maximum amplitude
            final short val = (short) ((dVal * 32767));
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSnd[idx++] = (byte) (val & 0x00ff);
            generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);

        }
    }

    void playSound(){
        final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
                AudioTrack.MODE_STATIC);
        audioTrack.write(generatedSnd, 0, generatedSnd.length);
        audioTrack.play();
    }
}