您好,我想通过耳机端口将数据从手机发送到手工时钟作为挑战。因此,我决定使用不同的音频频率作为不同的消息。例如,左声道1KHz表示小时,1.1KHz表示分钟,1.2KHz表示日,右声道1KHz表示1,1.1KHz表示2,依此类推。现在,我要发出声音了:
public class SetTimeAndDay_Activity extends Activity {
private final int duration = 1; // seconds
private final int sampleRate = 16000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private final double freqOfTone = 1000; // hz
private final byte generatedSnd[] = new byte[2 * numSamples];
Handler handler = new Handler();
int Hour, Minute, Day;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settime_layout);
//<editor-fold desc="Get Real Time">
final Calendar real = Calendar.getInstance();
Hour = real.get(Calendar.HOUR_OF_DAY);
Minute = real.get(Calendar.MINUTE);
Day = real.get(Calendar.DAY_OF_WEEK);
//</editor-fold>
//<editor-fold desc="Preset View">
TextView timetxt = findViewById(R.id.SetTime_Time_Txt);
TextView datetxt = findViewById(R.id.SetTime_Day_Txt);
ProgressBar progressBar= findViewById(R.id.SetTime_progressBar);
timetxt.setText(Hour + ":" + Minute);
datetxt.setText(getResources().getTextArray(R.array.WDay)[Day]);
progressBar.setMax(100);
progressBar.setProgress(1);
//</editor-fold>
// 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_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, numSamples,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}
}
但是有一些问题!
起初,我无法将声音duration
降低一秒。
第二个问题是我不知道何时可以发送下一条消息。我的意思是我怎么能意识到消息已发送。
下一个问题是,当我定义要播放的front_left通道时,它也从右通道播放。
最后一个问题是我无法意识到耳机端口是否已连接。 请以任何方式帮助我,不要给我减去。