对于初学者我是Android新手。我有一个Android应用程序,将音频记录12秒到原始文件,然后我使用lame将其转换为最终文件“mezzo.mp3”。然后,应用程序应将文件上载到服务器。但是,似乎代码永远不会执行上传部分。这是我的代码。
MainActivity.java
class UploadFileTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
String responseString = "";
try {
String url = "http://178.62.209.46:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//InputStream inputStream = new ;
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
protected void onPostExecute(String responseString){
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_LONG).show();
}
}
这里是计时器和UploadFileTask调用:
Button startButton = (Button) findViewById(R.id.StartButton);
startButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mRecMicToMp3.start();
CountDownTimer countDowntimer = new CountDownTimer(12000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mRecMicToMp3.stop();
Toast.makeText(getApplicationContext(), "Stopped recording Automatically ", Toast.LENGTH_LONG).show();
}};countDowntimer.start();
}
});
new UploadFileTask().execute();
计时器运行正常,并显示“自动停止录制”吐司。但是,似乎new UploadFileTask().execute();
永远不会运行。
我在做什么错误?
答案 0 :(得分:1)
你发布了许多代码。您应该只发布相关代码。在onClick上就足够了。
你有NetworkOnMainThreadException
。这也将在LogCat中清晰可见。你必须把互联网代码&#39;在AsyncTask或Thread中。
答案 1 :(得分:1)
在安装onclicklistener时,您正在开始执行asynctask。所以甚至在用户点击之前。您应该在录制完成后启动它。将该行直接放在吐司之后,告诉记录已停止。