Android - MediaPlayer (open failed: ENOENT (No such file or directory) - java

I asked a question earlier play video in new activity
What I want is when (Button) findViewById(R.id.pickVid); is clicked it calls PICK_VIDEO_REQUEST, then when the video is selected the new activity should open and play the video.
The guy that helped me said that I should use this.mPlayer.setDataSource(mStringFilePath); instead of FileInputStream
PROBLEM:
I am getting a error saying setDataSource failed.: status=0x80000000 with a black screen.
MainActivity
public class MainActivity extends AppCompatActivity {
Uri mMediaUri;
String vidFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pickVid = (Button) findViewById(R.id.pickVid);
//choose the video
pickVid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseVideo = new Intent(Intent.ACTION_GET_CONTENT);
chooseVideo.setType("video/*");
startActivityForResult(chooseVideo, PICK_VIDEO_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_VIDEO_REQUEST) {
if (resultCode == RESULT_OK) {
mMediaUri = data.getData();
vidFile = mMediaUri.toString();
Intent playVid = new Intent(MainActivity.this, PlayVideoAct.class);
playVid.putExtra("vidFile", vidFile);
startActivity(playVid);
}
}
}
PlayVideoAct
String mStringFilePath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playvideo);
mStringFilePath = getIntent().getStringExtra("vidFile");
}
public void surfaceCreated(SurfaceHolder holder) {
if (this.mPlayer == null) {
this.mPlayer = new MediaPlayer();
} else {
this.mPlayer.reset();
mPlayer.start();
}
try {
this.mMediaPlayer.setDataSource(mStringFilePath);
this.mPlayer.setDisplay(this.mSurfaceHolder);
this.mPlayer.prepare();
this.mPlayer.start();
this.mPlayer.pause();
Play();
} catch (Exception e) {
LogUtil.e(e, "Error in PlayVideoAct.surfaceCreate(SurfaceHolder)");
}
}
private void Play() {
mMediaPlayer.start();
if (this.mMediaPlayer.isPlaying()) {
this.mMediaPlayer.pause();
return;
}
if (this.isStop) {
this.mMediaPlayer.seekTo(this.leftPosition);
}
this.mImageViewButtonControls.setImageResource(R.drawable.pause);
}

Check video path, if it's correct then check if you have all necessary permissions like:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If yes, then depending on your Android version you may need to go to Settings -> Apps -> Your application -> Permissions and toggle those permissions manually.

Related

How To Create An App That Allows For Profile Picture Upload/Change permanently

I want to allow users to upload a profile picture in my app so far I have achieved this, but the problem is when I exit the app the profile picture disappears, so I was asking is there a way to store the picture in cache I'm using glide but don't know how to go about it
changing load defaults on my oncreate method but still does not work.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_IMAGE = 100;
#BindView(R.id.img_profile)
ImageView imgProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadProfileDefault();
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
GlideApp.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
}
private void loadProfileDefault() {
GlideApp.with(this).load(R.drawable.baseline_account_circle_black_48)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
}
#OnClick({R.id.img_plus, R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePickerActivity.showImagePickerOptions(this, new ImagePickerActivity.PickerOptionListener() {
#Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
#Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePickerActivity.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePickerActivity.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(MainActivity.this, ImagePickerActivity.class);
intent.putExtra(ImagePickerActivity.INTENT_IMAGE_PICKER_OPTION, ImagePickerActivity.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePickerActivity.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePickerActivity.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want the selected image to remain even after closing the app how do I go about it please enter
There are 2 ways to achieve your result.
Using Shared Preferences. You can save your variable uri to shared preference and fetch data from it next time. For this, you can check if uri is available in Shared Preference or not.
Using Room database library.
Below is the code using Shared Preference :
Your onCreate() will be like :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
loadImageFromSharedPrefernce();
}
private void loadImageFromSharedPrefernce() {
SharedPreferences prefs = getSharedPreferences("PREF_NAME", MODE_PRIVATE);
if (prefs.contains("imageUrl")){
String imageUrl = prefs.getString("imageUrl", "");
loadProfile(imageUrl); //your method
}
else {
loadProfileDefault(); //your method
}
}
Your onActivityResult() will be like :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
saveImageToSharedPreference(uri);
loadImageFromSharedPrefernce();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveImageToSharedPreference(Uri uri) {
SharedPreferences.Editor editor = getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putString("imageUrl", String.valueOf(uri));
editor.apply();
}
You should save profile pic URI in SharedPreference which is being received in onActivityResult() method. Adding the sample code below, have a look.
private void saveProfilePicLocal(String uri){
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putString("profile_uri", uri); // Storing string
editor.commit(); // commit changes
}
Now you have to call above function in onActivityResult() method like below.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
saveProfilePicLocal(uri.toString())
loadProfile(uri.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
After that, you should check whether you have any profile locally saved or not if there is any URI exists in SharedPreference read it and load otherwise load default one. Check the sample code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
//Check whether profile pic URI exists in Local SharedPreference
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
if (prefs.contains("profile_uri")){
String uri = pref.getString("profile_uri", null);
if(TextUtils.isEmpty(uri.trim())
loadProfileDefault();
else
loadProfile(uri);
}
}
Happy coding!.

Zxing Bar code scanner issue in Android

I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}

Destroy data on pressing back button in android

I have few activity files that contains almost same code as shown below. Well i have not included onDestroy and finish() method in all of my activity files, before moving forward i want to be sure of the code posted below.
public class Three extends AppCompatActivity {
Button forwardB,backwardB,homeB;
TextView textView2,textView4,textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
//Place advertisement here
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
//
//find widget by Id
forwardB = (Button) findViewById(R.id.forwardB);
backwardB = (Button) findViewById(R.id.backwardB);
homeB = (Button) findViewById(R.id.homeB);
textView2= (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4);
textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText("3/50");
//set text inside textView3 and textView4
textView2.setText("Apfel");textView4.setText("apple");
//set on click listener for forward,backward and home button
forwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Two.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
homeB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
backwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Four.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
After running the application i found a serious issue with data,it looks like android keeps data in background. How can i avoid this?
Everytime i run app and check the data it seems to be increasing.
Well this is my MainActivity.java:
public class MainActivity extends Activity {
Button btnflashcards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//create widget ids that are usable forw rest of the code
btnflashcards = (Button) findViewById(R.id.btnflashcards);
}
//on flash card button click
public void findFlashCards(View v){
Intent i = new Intent(this, FlashCardSelection.class);
startActivity(i);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
You will need to explicitly clear the application's user data every time you exit the aplication or at any point of time you want to during the use of your app.
Use this: ActivityManager's clearApplicationUserData() method
As per documentation this will:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
Give something like this a shot
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}

Error when trying to play audio file from URI

So I'm completely new to Android programming and I'm starting off by trying to make an app that allows users to edit audio files. Here is my code so far, which makes a user upload an audio file and play it:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
public String filePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.uploadbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), Uri.parse(filePath));
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
filePath = uri.getPath();
getFilePath(filePath);
TextView URI_Text = (TextView)findViewById(R.id.file_URI);
URI_Text.setText(filePath);
}
}
}
}
public String getFilePath (String filePath) {
return filePath;
}
}
However, I'm getting the error code E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab756e00
What am I doing wrong?
That error is not related to any of your code from your question. However, you are going wrong in other places.
getPath() is useless. The Uri should be treated as an opaque handle. Calling getPath() on a Uri, and expecting a file to be at that path, is akin to expecting there to be a /questions/33843271/error-when-trying-to-play-audio-file-from-uri path on your computer's hard drive, just because your browser happens to be showing a URL with that path.
Also, your access to the data represented by that Uri is short-lived. This is reminiscent of Web development, where you might be able to stream data from some URL for a while, but eventually your session times out. Saving the Uri is pointless. Either consume the data now (via a ContentResolver and openInputStream()), or don't bother with the data at all.

Android java : Text-to-Speech no sound

Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(
Change the implements OnInitListener to TextToSpeech.OnInitListener.
Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.

Categories

Resources