Sorry new to SOF and my question might seem a bit vague.
Using android studio, i'd like to be able to upload an audio file and a text file generated from the audio file, to firebase. They are linked, however I can only upload the audio file to the firebase realtime-database. Is there any way to combine the .3gp file and the .txt file and upload them? Thanks.
Edited: This is my code so far. It's quite messy just trying to get the files together. Thanks.
private ImageButton recordButton;
private TextView txtRec;
private MediaRecorder mRecorder;
private String mTextFileName = null;
private String mFileName = null;
private static final String LOG_TAG = "Record_Log";
private ProgressDialog mProgress;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
checkPermission();
final TextView txtRec = findViewById(R.id.speechOutput);
txtRec.setFocusable(false);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
recordButton = (ImageButton) findViewById(R.id.button);
mStorage = FirebaseStorage.getInstance().getReference();
mProgress = new ProgressDialog(this);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/recorded_audio.3gp";
mTextFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mTextFileName += "/recorded_text.txt";
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
txtRec.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
recordButton.findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.stopListening();
txtRec.setHint("You will see input here");
startRecording();
break;
case MotionEvent.ACTION_UP:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
txtRec.setText("");
txtRec.setHint("Listening...");
stopRecording();
break;
default:
break;
}
return false;
}
});
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
uploadAudio();
}
private void uploadAudio() {
mProgress.setMessage("Sending Audio...");
final StorageReference filepath = mStorage.child("Audio").child("new_audio.3gp");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
txtRec.setText("Sent");
}
});
}
Related
I am developing an app in java in the android studio IDE, the idea is that after logging in with my username and password, I can be redirected to a new view where a user profile is shown with the name, email and profile image. Currently I can log in and after that it redirects to the user profile but I don't know how to get the name, email and profile image.Then I leave you my code in case you have the time to help me, thank you very much for reading:
loggin.class
public class loggin extends AppCompatActivity {
//variable twitter
Button twitterButton;
//TwitterLoginButton login;
private static final String TAG = "Twitter4j";
private static Twitter twitter;
private static final String APIConsumerKey = "xxxx";
private static final String APIConsumerSecretKey = "xxxx";
private static final String CALLBACK_URL = "http://myurl";
private static RequestToken twitterRequestToken;
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeTwitter(loggin.this);
}
});
}
private static void initializeTwitter(final Activity activity) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(APIConsumerKey);
configurationBuilder.setOAuthConsumerSecret(APIConsumerSecretKey);
twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
new Thread(new Runnable() {
#Override
public void run() {
User user;
try {
twitterRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("LoginActivity", String.valueOf(twitterRequestToken));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Open Dialog for authentication.
Intent intent = new Intent(activity, TwitterAuthActivity.class);
if (twitterRequestToken != null) {
intent.putExtra("TwitterReqTokenUrl", twitterRequestToken.getAuthenticationURL());
activity.startActivity(intent);
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception " + e.getMessage());
}
}
}).start();
}
}
twitterAuthActivity
public class TwitterAuthActivity extends AppCompatActivity {
private static final String TAG = "Twitter4j";
private static final String TWITTER_CALLBACK_URL = "http://www.stackoverflow.com"; //"x-oauthflow-twitter://twitterlogin";
private ProgressDialog progressDialog;
private String twitterRequesTokenUrl;
private WebView twitterWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_twitter);
twitterWebView = findViewById(R.id.TwitterWebView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
twitterRequesTokenUrl = extras.getString("TwitterReqTokenUrl");
}
progressDialog = new ProgressDialog(this);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
//Setup WebView
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
twitterWebView.setVerticalScrollBarEnabled(false);
twitterWebView.setHorizontalScrollBarEnabled(false);
twitterWebView.setWebViewClient(new TwitterWebViewClient());
WebSettings webSettings = twitterWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
twitterWebView.loadUrl(twitterRequesTokenUrl);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int[] l = new int[2];
twitterWebView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + twitterWebView.getWidth(), l[1] + twitterWebView.getHeight());
if (!rect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
finish();
}
}
return super.dispatchTouchEvent(ev);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean response = false;
if (url.contains(TWITTER_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
//This uri could be saved as access token.
Log.i(TAG, "shouldOverrideUrlLoading() uri " + uri.getPath());
Intent intent=new Intent(TwitterAuthActivity.this,MainActivity.class);
startActivity(intent);
finish();
response = true;
}
return response;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(TwitterAuthActivity.this, "Upps! something happened, retry later!.", Toast.LENGTH_LONG).show();
finish();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progressDialog.isShowing() && !isFinishing() && !isDestroyed()) {
progressDialog.dismiss();
}
twitterWebView.setVisibility(View.VISIBLE);
}
}
}
The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}
I am trying to make simple app just for learning purpose thats record an audio clip then upload the file to the firebase and here is my code
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
Button recordeButton ;
TextView recorderLable ;
private MediaRecorder recorder;
private String fileName = null ;
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private MediaPlayer player = null;
ProgressDialog progressDialog ;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
recordeButton = findViewById(R.id.recordeButton) ;
recorderLable = findViewById(R.id.recordeLable) ;
fileName = getExternalCacheDir().getAbsolutePath();
fileName += "/audiorecordtest.3gp";
ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
progressDialog = new ProgressDialog(this) ;
recordeButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
startRecording();
recorderLable.setText("recording started");
} else if (event.getAction() == MotionEvent.ACTION_UP){
stopRecording();
recorderLable.setText("recording stopped");
}
return false ;
}
});
}
private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(fileName);
try {
recorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
recorder.start();
}
private void stopRecording() {
recorder.stop();
recorder.release();
recorder = null;
uploadAudio();
}
private void uploadAudio() {
progressDialog.setMessage("UPLOADING ...");
progressDialog.show();
String uniqueID = UUID.randomUUID().toString() ;
final StorageReference filePath = mStorage.child("Audio").child(uniqueID + ".mp3") ;
Uri uri = Uri.fromFile(new File(fileName)) ;
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
recorderLable.setText("AUDIO UPLOADED \uD83D\uDE0A");
filePath.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
final Uri path = task.getResult();
Log.i("AUDIO_URI", path.toString());
}
}
}) ;
}
}) ;
}
}
the problem is I've uploaded the file successfully but when I try to play it in the firebase nothing happen and length of the file is 0:00 which means that there is a problem in recording process not in uploading
I'm trying play an audio file with the mediacontroler in my android application. When playing audio the seekbar does not move.I looked mediacontroler function. But I could not find a function for updating seekbar.
please advice.
public class Show_subject_Activity extends Activity
implements MediaController.MediaPlayerControl, MediaPlayer.OnBufferingUpdateListener {
private RatingBar box_litner;
private MediaController mController;
private MediaPlayer mPlayer;
private Cursor cur;
int bufferPercent = 0;
DB_Nabege_helper db_nabege = new DB_Nabege_helper(this);
private String voicefileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_subject);
box_litner = (RatingBar) findViewById(R.id.ratingBar1);
mController = (MediaController) findViewById(R.id.mediaController_voice);
mController.setAnchorView(null);
db_nabege.open();
cur = db_nabege.getSubject(Intent_values.id_subject);
voicefileName = getVoiceFileName();
db_nabege.close();
}
#Override
public void onResume() {
super.onResume();
mPlayer = new MediaPlayer();
// Set the audio data source
try {
mPlayer.setDataSource(this, getUriVoice());
mPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
// Set an image for the album cover
// coverImage.setImageResource(R.drawable.icon);
mController.setMediaPlayer(this);
mController.setEnabled(true);
}
private Uri getUriVoice() {
File voiceFile = null;
try {
voiceFile = new File(Environment.getExternalStorageDirectory().getPath() + "/nabege" + File.separator
+ "audio" + File.separator + voicefileName);
} catch (Exception e) {
Log.d("log", e.toString());
}
Uri voiceUri = Uri.fromFile(voiceFile);
return voiceUri;
}
#Override
public void onPause() {
super.onPause();
mPlayer.release();
mPlayer = null;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return super.onTouchEvent(event);
}
// MediaPlayerControl Methods
#Override
public int getBufferPercentage() {
return bufferPercent;
}
#Override
public int getCurrentPosition() {
return mPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mPlayer.isPlaying();
}
#Override
public void pause() {
mPlayer.pause();
}
#Override
public void seekTo(int pos) {
mPlayer.seekTo(pos);
}
#Override
public void start() {
mPlayer.start();
}
// BufferUpdateListener Methods
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
bufferPercent = percent;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
You can update the seekbar yourself, e.g.:
final Handler mHandler = new Handler();
final Runnable mUpdateSeekbar = new Runnable() {
public void run() {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
mSeekBar.setMax(mMediaPlayer.getDuration());
mHandler.postDelayed(this, 1000);
}
};
Post the runnable in onResume and mHandler.removeCallbacks(mUpdateSeekbar) in onPause.
From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.