我在soundcloud服务器上传音频但是当我点击上传按钮时它会抛出FileNotFoundException。从服务器上传响应后必须生成.plss帮助我们。如果我在某处犯错误,请纠正我。
有2种情况,其中执行上传功能。 1.只记录一页故事音频并将其强化(在这种情况下音频正在上传)。 2.录制多个页面故事,其中在上传第一页音频后,第二页将作为我服务器的响应。(在这种情况下,它抛出FileNotFound异常)。
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG,"Reponse Check for sound upload login :"+response);
// Log.d(TAG,"Object Check :"+json);
try {
JSONObject json = new JSONObject(response);
access_token = json.getString("access_token");
expires_in = json.getString("expires_in");
refresh_token = json.getString("refresh_token");
// doFileUpload();
new AsyncTaskRunner().execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Error Response Check :" + error);
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", client_id);
params.put("client_secret",client_secret);
params.put("grant_type",grant_type);
params.put("username",username);
params.put("password",user_password);
Log.d(TAG, "Params :" + params);
return params;
}
}; AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
});
}
private void mergeAudioFiles(){
try {
File tempFolder = new File(mRawAudioFolder.getPath());
Movie[] movies = new Movie[tempFolder.listFiles().length];
int i = 0;
for (File saveTempFile : tempFolder.listFiles()) {
try {
movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
final Movie finalMovie = new Movie();
List<Track> audioTracks = new ArrayList<>();
for (Movie movie : movies) {
for (Track track : movie.getTracks()) {
}
}
finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
final Container container = new DefaultMp4Builder().build(finalMovie);
mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
final FileOutputStream fos = new FileOutputStream(mergedFile);
FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
container.writeContainer(fc);
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createAudioFolder() {
File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
mRawAudioFolder = new File(movieFile, "Temp");
mAudioFolder = new File(movieFile, "The Tagore Project");
if (!mAudioFolder.exists()) {
mAudioFolder.mkdirs();
}
if (!mRawAudioFolder.exists()) {
mRawAudioFolder.mkdirs();
}
}
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
public void forwardtoOurServer() {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Audio Upload Response Check :" + response);
Log.d(TAG,"Object Check :"+response);
try {
JSONObject json = new JSONObject(response);
String code = json.getString("code");
if (String.valueOf(code).equals("200")) {
JSONObject upload = json.getJSONObject("upload");
JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
String content = Composition.getString("content");
String pageno = Composition.getString("pageno");
String tocid = Composition.getString("table_of_content_id");
String wrd_count = Composition.getString("wordcount");
String tocName = TableofContents.getString("name");
} else {
String errorMsg = json.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error Response Check :" + error);
}
}) {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("data[Booking][id]",bookingId);
params.put("data[Booking][contributor_id]",contributor_id);
params.put("data[Booking][table_of_content_id]",tocId);
params.put("data[Booking][cdn_id]",vs_cdn_id);
params.put("data[Booking][secret_token]",secret_token);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date now = new Date();
String strDate = sdf.format(now);
params.put("data[Booking][uploaded_on]",strDate);
Log.d(TAG, "Params :" + params);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("UUID", device_uuid);
headers.put("APPID", "2A192A0C22");
headers.put("USERID", "1");
headers.put("PLATFORM", "Andriod");
headers.put("APP_REQUEST", "1");
headers.put("PLATFORMVERSION",androidOS);
return headers;
}
};
AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(RecordComposition.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(RecordComposition.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
HttpURLConnection conn = null;
//DataOutputStream dos = null;
//DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "https://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(mergedFile);
// open a URL connection to the Servlet
URL url = new URL (urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
try {
BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
Log.e("Debug","Before while");
while (( str = inStream.readLine() ) != null)
{
Log.e("Debug","Server Response "+str);
JSONObject response = new JSONObject(str);
vs_cdn_id = response.getString("id");
secret_token = response.getString("secret_token");
forwardtoOurServer();
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
日志:
File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
error: https://api.soundcloud.com/tracks
java.io.FileNotFoundException: https://api.soundcloud.com/tracks
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
答案 0 :(得分:0)
在您的Activity类
中添加此代码@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> types = new ArrayList<>();
//add item to manes and types array
ListViewAdapter customList = new ListViewAdapter(this, names, types);
list = (ListView) findViewById(R.id.lv);
list.setAdapter(customList);
}
这是ListViewAdapter类
public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;
public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
super(context, R.layout.item_rating_rows, names);
this.context = context;
this.names = names;
this.types = types;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
Button btn = (Button) listViewItem.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("__onclick", "" + view.getId());
}
});
return listViewItem;
}
}
答案 1 :(得分:0)
在清单中给予许可......
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />