问题
I've been stuck on this problem for days. I'm at the stage now where I'm just trying to get a working example to build from, but I can't even reach that point.
My question is based on this example. I've included the source (and solution) into my own code, and can see the buffer is being written to, but no sound comes from the device. I'm struggling to identify how to debug this further.
package com.example.audio;
import com.example.R;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
public class Synth {
private static final String TAG = Synth.class.getSimpleName();
private AudioTrack audioTrack;
private Context context;
public Synth(Context context) {
this.context = context;
int minBufferSize = AudioTrack.getMinBufferSize(22050, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 22050, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
}
public void playSound() {
audioTrack.play();
int i = 0;
int bufferSize = 512;
byte [] buffer = new byte[bufferSize];
InputStream inputStream = context.getResources().openRawResource(R.raw.mysample);
try {
int writes = 0;
while((i = inputStream.read(buffer)) != -1) {
writes++; audioTrack.write(buffer, 0, i);
}
Log.d(TAG, "Wrote " + writes + " times." );
} catch (IOException e) {e.printStackTrace();}
try {inputStream.close();} catch (IOException e) {e.printStackTrace();}
}
}
(To replicate project: make new project, include this class, add the audio mentioned below, create an instance of the Synth
, then fire the playSound
public function)
Obviously I can't upload audio, or guarantee it's persistence in a web folder, but this tool will generate a WAV file exactly like I am using (change the sample rate to 22.05kHz and press 'download .wav file')
I realize that the STREAM_MUSIC
and MODE_STREAM
seem out of place in this example. I am using those flags/mode because I know I will need to use AudioTrack with these modes later in development, and really am just trying to get sound coming out of the device for the moment.
Can anyone suggest debugging steps, or see what the problem with the playback is? Any help appreciated.
回答1:
I've determined the problem I had originally when I first raised this question. Hopefully it helps some other people out there...
As it turns out, the app wasn't playing audio at the time when I was adjusting the volume, so the volume that was actually maxed was the system/ringtone volumes, and not the 'music, video games, and other media' volume, which was muted.
来源:https://stackoverflow.com/questions/31354338/audiotrack-in-mode-stream-has-no-sound