我在使用audiotrack(AudiTrack對象)播放的android中生成音調,但我想將此音調保存爲電話或SD卡中的音頻文件。代碼是將文件保存爲音頻文件後未播放文件
public class MainActivity extends Activity {
// int j=2;
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 = 500; // 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.activity_main);
}
@Override
protected void onResume() {
super.onResume();
// Use a new tread as this can take a while
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));
//System.out.println("the value is ::"+sample[i]);
}
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
int loop = 0;
boolean flip =false;
for (double dVal : sample) {
short val = (short) (dVal * 32767);
generatedSnd[idx++] = (byte) (val & 0x00ff);
//System.out.println("the value at address"+generatedSnd[idx-1]);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
if(flip)
{
generatedSnd[idx-1]=(byte)(generatedSnd[idx-1]*2);
generatedSnd[idx-2]=(byte)(generatedSnd[idx-2]*2);
}
System.out.println("the value is:"+generatedSnd[idx-1]);
System.out.println("the value is::"+generatedSnd[idx-2]);
loop++;
if(loop==16){
loop=0;
flip=!flip;
}
}
}
void playSound(){
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, numSamples,
AudioTrack.MODE_STATIC);
// audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.write(generatedSnd, 0, numSamples);
audioTrack.play();
String sFileName="tonegenerator.mp3"; //String sBody =generatedSnd.toString();
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
// FileWriter writer = new FileWriter(gpxfile);
FileOutputStream writer=new FileOutputStream(gpxfile);
writer.write(generatedSnd, 0, numSamples);
//writer.write(generatedSnd, 0, numSamples);
// writer.write(generatedSnd);
// writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
// importError = e.getMessage();
// iError();
}
}
}
現在該文件也被保存到名爲「Notes」的文件夾中。文件tonegenerator.mp3不能在手機和系統中播放。如果我的代碼不正確的存儲它。那麼我們應該如何存儲它。
僅僅因爲您將文件結尾爲「.mp3」,文件就不會成爲有效的mp3文件。你正在寫的文件看起來像沒有頭壓縮的未壓縮PCM。 – Michael