Im following tutorials on youtube and I'm stuck https://www.youtube.com/watch?v=pPpVZ8YZXHk&t=62s
in the tutorial after entering
package com.example.oneilbogle.radiov1;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b_play;
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
String stream = "http://142.4.217.133:8647/stream";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button) findViewById(R.id.b_play);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
mediaPlayer.setDataSource(strings[0]);
return prepared;
}
}
}
mediaPlayer.setDataSource(strings[0]);
the author uses a try/catch option but i get a different option
what should i do ?
You are messing the parameters names around.
Try with either:
protected Boolean doInBackground(String... params) {
mediaPlayer.setDataSource(params[0]);
return prepared;
}
or
protected Boolean doInBackground(String... strings) {
mediaPlayer.setDataSource(strings[0]);
return prepared;
}
so what i did was i changed it to stream
mediaPlayer.setDataSource(stream);
Related
Hii i'm working on a project in which I have taken rss feeds from a website and embedded the data into recycler view. The recycler view is working fine till page 3 but on page 4 it doesn't loads...
I have attached the code below. Is there anyone who can help me solving the issue??
You can check out the video here: https://drive.google.com/file/d/1JxUVgfBfcZR_6eThFNZ2nenEIz3UykCm/view?usp=sharing
package com.example.myapplication;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.myapplication.Adapter.FeedAdapter;
import com.example.myapplication.Common.HTTPDataHandler;
import com.example.myapplication.Model.RSSObject;
import com.google.gson.Gson;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RSSObject.RssObject rssObject;
private String rss_link="http://www.freejobalert.com/feed/";
int pageCount = 1;
private final String rss_to_json_api = "https://api.rss2json.com/v1/api.json?rss_url=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext(),LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
loadRss();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==R.id.menu_refresh)
{
loadRss();
pageCount=1;
}
if(item.getItemId()==R.id.next)
{
rss_link+="?paged=";
pageCount++;
rss_link+=pageCount;
loadRss();
}
if(item.getItemId()==R.id.previous)
{
if(pageCount>2)
{
rss_link+="?paged=";
pageCount--;
rss_link+=pageCount;
loadRss();}
else{
loadRss();
}
}
return true;
}
private void loadRss() {
AsyncTask<String, String, String> loadRssAsync = new AsyncTask<String, String, String>() {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Please Wait...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String result;
HTTPDataHandler httpDataHandler = new HTTPDataHandler();
result = httpDataHandler.getHTTPData(strings[0]);
return result;
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
rssObject = new Gson().fromJson(s, RSSObject.RssObject.class);
FeedAdapter adapter = new FeedAdapter(rssObject, getBaseContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
StringBuilder url_get_data = new StringBuilder(rss_to_json_api);
Log.e("Test",""+ rss_link);
url_get_data.append(rss_link);
loadRssAsync.execute(url_get_data.toString());
rss_link="http://www.freejobalert.com/feed/";
}
}
I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (SeekBar)findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
SeekBar seekBar = (SeekBar)v;
int playPosition = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
I am trying to write an android app that streams from an icecast server when you click play. This is for a radio station that I help out in my area, and they need to get out in the community, and be able to advertise. I have written some android apps before, but my experience with this is limited.
There are no errors in the code according to android studio, and the app does everything the way it is supposed to except play the stream. I have tested the stream on my browser, and it is up and running.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button b_play;
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
String stream = "<server address>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button) findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("LOADING...");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(started) {
started = false;
mediaPlayer.pause();
b_play.setText("PLAY");
}else{
started = true;
mediaPlayer.start();
b_play.setText("PAUSE");
}
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean>{
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aboolean) {
super.onPostExecute(aboolean);
mediaPlayer.start();
b_play.setEnabled(true);
b_play.setText("PLAY");
}
}
#Override
protected void onPause() {
super.onPause();
if(started) {
mediaPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if(started) {
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(prepared){
mediaPlayer.release();
}
}
}
Icecast has delay picking up Android apps. If you have 32k streaming it can take up to 40 seconds for the stream to load. 64k can take awhile also.
Shoutcast servers pick up almost instantly.
https://androidaudio.info/android-audio-buffering-issues-with-32k-acc-icecast-server/
This is my code:
package com.example.pembroke.finalalgorhythmic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button asdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asdf = (Button) findViewById(R.id.keybutton);
asdf.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
}
What I want to do, is create a character array, so that I can use media player class to play certain sounds based on the user input after my button is clicked. Any ideas?
Have you tried
notes.toCharArray() yet?
EDIT: Long version
EDIT 2: Sample implementation
MediaPlayer mp;
char[] currentNotes;
int noteIndex;
// Create the mp in onCreate and register your onCompletion callback
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
currentNotes = notes.toCharArray();
noteIndex = 0;
mp.setDataSource(getNoteResource(currentNotes[0]));
mp.start();
}
// Convert tone values into
public int getNoteResource(char tone) {…}
#Override
public void onCompletion(MediaPlayer mp) {
if(++noteIndex < currentNotes.length) {
mp.setDataSource(getNoteResource(currentNotes[noteIndex]));
mp.start();
}
}
I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!