我正在尝试使用AudioTrack播放音频。
我可以正常速度播放。 我可以慢慢播放。
但我无法快速播放。
如何快速播放?
try (InputStream is = getResources().openRawResource(R.raw.sample)) {
byte[] bytes = new byte[is.available()];
is.read(bytes);
final int SAMPLING_RATE = 48000;
final int size = AudioTrack.getMinBufferSize(
SAMPLING_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack audioTrack = new AudioTrack.Builder()
.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build())
.setAudioFormat(new AudioFormat.Builder()
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(SAMPLING_RATE)
.build())
.setBufferSizeInBytes(size)
.build();
audioTrack.setPlaybackRate(SAMPLING_RATE);
PlaybackParams params = audioTrack.getPlaybackParams();
//params.setSpeed(1.0f); // available
//params.setSpeed(0.5f); // available
params.setSpeed(1.5f); // not available
audioTrack.setPlaybackParams(params);
audioTrack.play();
audioTrack.write(bytes, 44, bytes.length - 44);
audioTrack.stop();
audioTrack.flush();
} catch (IOException e) {
Log.e(TAG, e.toString());
}
params.setSpeed(1.5f)不可用。
我收到以下错误消息。
06-14 09:24:55.714 957-12866/? D/AES: onEndOfErrorDumpThread: data_app_crash Process: com.example.audiotracksample
Flags: 0x38e8bf46
Package: com.example.audiotracksample v1 (1.0)
Foreground: Yes
Build: COVIA/CP-L45s/CP-L45s:7.0/NRD90M/1502850909:user/release-keys
java.lang.IllegalArgumentException: arguments out of range
at android.media.AudioTrack.native_set_playback_params(Native Method)
at android.media.AudioTrack.setPlaybackParams(AudioTrack.java:1590)
at com.example.audiotracksample.MainActivity$AudioThread.run(MainActivity.java:69)
at java.lang.Thread.run(Thread.java:761)
答案 0 :(得分:0)
您可以增加参数SAMPLING_RATE
答案 1 :(得分:0)
AudioTrack:不建议将流类型用于音量控制以外的其他操作
答案 2 :(得分:0)
根据文档,缓冲区也需要很大以提高速度。
如果你想将速度提高 2 倍,你应该使用至少两倍于最小缓冲区大小的缓冲区
audioTrack = AudioTrack(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build(),
AudioFormat.Builder()
.setChannelMask(channelConfig)
.setSampleRate(sampleRateInHz)
.setEncoding(audioFormat)
.build(),
max(minBufferSize, bufferSize) * 2, // see here.
AudioTrack.MODE_STREAM,
AudioManager.AUDIO_SESSION_ID_GENERATE
)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
val playbackParams = PlaybackParams()
playbackParams.speed = 2F
audioTrack.playbackParams = playbackParams
}