Android播放PCM,请写出代码
时间: 2024-02-27 15:58:35 浏览: 106
以下是一份简单的 Android 播放 PCM 的代码:
```java
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
public class PCMPlayer {
private AudioTrack audioTrack;
private Thread playThread;
public PCMPlayer() {
int sampleRateInHz = 44100;
int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, AudioTrack.MODE_STREAM);
}
public void start() {
playThread = new Thread(new Runnable() {
@Override
public void run() {
audioTrack.play();
// TODO: 将 PCM 数据写入 audioTrack
}
});
playThread.start();
}
public void stop() {
if (audioTrack != null) {
audioTrack.stop();
audioTrack.release();
audioTrack = null;
}
if (playThread != null) {
try {
playThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
playThread = null;
}
}
}
```
这份代码创建了一个 `AudioTrack` 对象,并在 `start` 方法中启动一个新的线程,用于播放 PCM 数据。你需要在此方法中将 PCM 数据写入 `audioTrack`。`stop` 方法用于停止播放并释放资源。
阅读全文