Saving android specific button sound - android

I have a soundboard and I am trying to save sounds as a ringtone or notification but it is saving the same sound each time which I think is being pulled from " here can anyone shed some light? Thinking it needs to change R.raw.sound1 so it pulls in the sound of which ever button is clicked to bring up the context menu.
I've added the loop and integrs code which makes the buttons work just in case.
EDIT FULL CODE - Error: selectedSoundId cannot be resolved
:- for each three bits of code that say selectedSoundId
Not sure if I have done this bit:
Where and how do I add this?
The "int selectedSoundId" should be declared as a class field, to make it accessible in every class method.
public class Soundboard extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.soundboard);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.backdoors etc};
final int[] soundIds = { R.raw.back_doors etc };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
else if(item.getTitle()=="Notification"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
//Save into Ring tone Folder
public boolean savering(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false; }
String path="/sdcard/media/audio/ringtones/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
//Save in Notification Folder
public boolean savenot(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false; }
String path="/sdcard/media/audio/notifications/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Notification");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
}

I don't see where you are replacing the content of
R.raw.sound1
which you are passing as an argument, thus, as I can observe in your code, you are saving the same sound every time you call the saving methods.
EDIT:
Create int variable which will hold the info about last selected sound:
int selectedSoundId;
In onClickListener set the selectedSoundId to sound id connected with current button:
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
//rest of the code
}
Pass the selectedSoundId to savering and savenot methods:
savering(selectedSoundId);
savenot(selectedSoundId);
Hope this helps.
EDIT 2: I'm pasting your code with my corrections.
Ad.2. This is the part when you need to save the info about current sound id.
final int[] buttonIds = { R.raw.sound1 "etc all buttons here"};
final int[] soundIds = {R.raw.sound1 "etc all sounds here"};
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
Ad.3. This is the part of calling the savering and savenot methods.
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}

Related

Writing contacts on an xml file in Android

Hello I have this code(pasted below) which reads and displays the phone contacts in a ListView. Apart from this it should also have one more functionality and that is it should be able to write the contacts as they are being read onto to a xml file. I want to store that xml in my SD card.Please check the code below.
public class ContactsListActivity extends Activity implements
OnItemClickListener
{
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
XmlSerializer serializer = Xml.newSerializer();
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml");
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
//we have to bind the new file with a FileOutputStream
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
//we set the FileOutputStream as output for the serializer, using UTF-8 encoding
try {
serializer.setOutput(fileos, "UTF-8");
//Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
//create a new file called "new.xml" in the SD card
//we create a XmlSerializer in order to write xml data
try {
//set indentation option
// serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
//start a tag called "root"
serializer.startTag(null, name);
//i indent code just to have a view similar to xml-tree
serializer.startTag(null, "name");
serializer.text(name);
serializer.endTag(null, "name");
serializer.startTag(null, "phonenumber");
serializer.text(phoneNumber);
serializer.endTag(null, "phonenumber");
serializer.endTag(null, name);
//write xml data into the FileOutputStream
serializer.flush();
//finally we close the file stream
fileos.close();
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
try {
//write xml data into the FileOutputStream
// serializer.flush();
//finally we close the file stream
// fileos.close();
serializer.endDocument();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
phones.close();
ContactAdapter objAdapter = new ContactAdapter(
ContactsListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(
ContactsListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
#SuppressWarnings("deprecation")
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactsListActivity.this)
.create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
}
I got this code off the internet and it has a flaw. Only the last read contact is getting added to the xml file on my sd card. When i debugged the code, It shows proper traversing of the code and all contacts.
I would like to add all the read contacts onto the xml file am storing. Any help or correction in this code is very much appreciated. Thanks in advance.

android ringtones - how to add ringtones getting from URL path

I wonder is there any way to set ringtones that get from url path when user long click on ringtones name in Activity.
Bellow code i tried to change filnal path from R.raw.sound1 to URL path, but still can't.
Anyone can give me a clue of how to set ringtone getting file from URL?
Here is my code
final MediaPlayer ring01 = MediaPlayer.create(this, R.raw.sound1);
// play sound files on clicks
Button s01 = (Button) findViewById(R.id.btnring01);
s01.setText(this.getString(R.string.title01));
s01.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
ring01.prepare();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ring01.start();
}
});
registerForContextMenu(s01);
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Tab Here To Save As Ringtone");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Tab Here To Save As Ringtone"){function1(item.getItemId());}
else {return false;}
return true;
}
public boolean function1(int ressound){
String soundname = "";
switch(ressound)
{
case R.id.btnring01:
ressound=R.raw.aftermath;
soundname = (this.getString(R.string.title01));
break;
}
//and so on and so on.....
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename=soundname+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, soundname);
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "Sokun Kanha");
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
//values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
//values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
//values.put(MediaStore.Audio.Media.IS_ALARM, true);
//values.put(MediaStore.Audio.Media.IS_MUSIC, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);

Android how to record music from media player

I'm working on a project where I'm playing music over url using android build in media player. The things that I want to achieve this is to be able to save the streaming data in a file on sd card. I've tried to do this using android build in media recorder, but it's recording everything around the phone, not only the sound which is coming from media player.
So my question is which is the best way to achieve this?
Here is an example which I've tested already, but I can't play the mp3 file after that to see if everything went ok :
Log.e("URL AGAIN","url : "+url);
try {
if(!isrecording){
URL urlStream = new URL(url);
InputStream inputStream = urlStream.openStream();
Log.d("", "urlStream.openStream()");
String filename = Environment.getExternalStorageDirectory().getAbsolutePath();
filename += "/deliciousradio.mp3";
File outputSource= new File(filename);
fileOutputStream = new FileOutputStream(outputSource);
Log.d("", "FileOutputStream: " + outputSource);
int bytesRead = -1;
isrecording = true;
byte[] buffer = new byte[30 * 1024];
while ((bytesRead = inputStream.read(buffer)) > 0) {
byte[] buffer2 = new byte[bytesRead];
fileOutputStream.write(buffer2);
Log.d("","bytes size :"+buffer2.length);
Log.d("","bytesRead : "+bytesRead);
}
} else if(isrecording){
fileOutputStream.close();
}
} catch(Exception e){}
The problem here is that I'm receiving 30 as length of buffer2, and i cannot undersand why.
Thanks for any kind of help!
Button recstart, recstop,replay;
//onCreate
File f;
File externalStorage;
String path = "";
MediaRecorder recorder;
Timer time;
String filename1 = "";
boolean s = false;
externalStorage = Environment.getExternalStorageDirectory();
String sdCardPath = externalStorage.getAbsolutePath();
recorder = new MediaRecorder();
path = sdCardPath + "/";
recstart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
try {
throw new IOException("SD Card is not mounted. It is "
+ state + ".");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + "_" + minutes + "_" + seconds;
filename1 = "phonecall_at" + curTime + ".mp4";
if (recorder == null) {
recorder = new MediaRecorder();
}
f = new File(path, filename1);
try {
s = f.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
// Toast.makeText(AudioRecording.this,"hiiiii...."+e1.getMessage(),2000).show();
e1.printStackTrace();
}
// MediaRecorder.AudioSource.VOICE_CALL +
// MediaRecorder.AudioSource.MIC
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK
// + MediaRecorder.AudioSource.VOICE_DOWNLINK );
if (s == true) {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(f.getAbsolutePath());
// record.setText("stop");
// record.setBackgroundColor( Color.BLUE);
// Toast.makeText(AudioRecording.this, String.valueOf(s),
// 3000).show();
try {
recorder.prepare();
Toast.makeText(AudioRecording.this, "Recording starts",
5000).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(".................................",
"" + e.toString());
}
recorder.start();
} else {
Toast.makeText(getApplicationContext(),
"No space Left on device", 2000).show();
}
/*
* try { recorder.prepare(); Toast.makeText(Recordingvoice
* .this,"Recording starts",5000).show(); recorder.start();
*
*
* } catch (IllegalStateException e) { // TODO Auto-generated
* catch block e.printStackTrace(); } catch (IOException e) { //
* TODO Auto-generated catch block // e.printStackTrace(); }
*/
}
});
recstop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (s == true) {
Toast.makeText(AudioRecording.this, "Recording stopped",
2000).show();
if (recorder == null) {
recorder = new MediaRecorder();
}
if (recorder != null) {
recorder.stop();
recorder.release();
}
recorder = null;
// time.cancel();
// uploadCode();
}
}
});
replay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (f.exists()) {
Toast showMsg = Toast.makeText(getApplicationContext(), "Playing", Toast.LENGTH_SHORT);
showMsg.show();
String path = f.getAbsolutePath();
Uri myUri = Uri.parse(path);
MediaPlayer mp = new MediaPlayer();
mp.setLooping(false);
mp = MediaPlayer.create(AudioRecording.this, myUri);
mp.start();
}
}
});

display all textfiles in listview created by your app

The code creates a text file in local memory, but how do I get all files created by my application in a list view:
public class newfile extends Activity {
public EditText textBox,textbox2;
FileOutputStream fos=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newfile);
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
textBox = (EditText) findViewById(R.id.txtText1);
textbox2 = (EditText) findViewById(R.id.fname);
String FILENAME = textbox2.getText().toString();
String value = textBox.getText().toString();
try{
fos = openFileOutput(FILENAME,MODE_WORLD_WRITEABLE);
}
catch(IOException e)
{
e.printStackTrace();
}
byte[] buffer = value.getBytes();
try {
fos.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_LONG).show();
finish();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You can get a list all application files using Context.fileList. Then use ArrayAdapter to populate your list view

Receiving Info of a ShoutCast stream on Android

I am currently making an app to go with my online radio site, I am coding it with Android 2.2 (API 8) and I have got the Shoutcast Stream working with two buttons.
Here is the code on my main class:
public class GrooveOfMusicRadioActivity extends Activity {
/** Called when the activity is first created. */
MediaPlayer mediaPlayer;
Button start, stop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.pause();
}
});
String url = "http://67.212.165.106:8161"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So I was wondering so how do I receive the stream title,song,artist etc.. and make it appear
The main XML is in a relative layout
Thanks, I am a total noob when it comes to programming.
Thanks mark :)
I just had to get meta data myself, I basically did the same stuff from: Pulling Track Info From an Audio Stream Using PHP. A lot of data is in the headers so you can use those, but all I wanted was the Stream Title, so thats what I got.
Activity mainAct = this;
public void getNowPlaying(View v) {
Log.w("getNowPlaying", "fired");
new Thread(new Runnable() {
public void run() {
String title = null, djName = null;
try {
URL updateURL = new URL(YOUR_STREAM_URL_HERE);
URLConnection conn = updateURL.openConnection();
conn.setRequestProperty("Icy-MetaData", "1");
int interval = Integer.valueOf(conn.getHeaderField("icy-metaint")); // You can get more headers if you wish. There is other useful data.
InputStream is = conn.getInputStream();
int skipped = 0;
while (skipped < interval) {
skipped += is.skip(interval - skipped);
}
int metadataLength = is.read() * 16;
int bytesRead = 0;
int offset = 0;
byte[] bytes = new byte[metadataLength];
while (bytesRead < metadataLength && bytesRead != -1) {
bytesRead = is.read(bytes, offset, metadataLength);
offset = bytesRead;
}
String metaData = new String(bytes).trim();
title = metaData.substring(metaData.indexOf("StreamTitle='") + 13, metaData.indexOf(" / ", metaData.indexOf("StreamTitle='"))).trim();
djName = metaData.substring(metaData.indexOf(" / ", metaData.indexOf("StreamTitle='")) + 3, metaData.indexOf("';", metaData.indexOf("StreamTitle='"))).trim();
Log.w("metadata", metaData);
is.close();
} catch (MalformedURLException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace(); }
final String titleFin = title;
final String djNameFin = djName;
mainAct.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mainAct, titleFin + "\n" + djNameFin, Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
What you're using to play the stream has no knowledge of (and doesn't care about) the metadata. You're going to have to deal with that separately.
See these posts for something you can easily adapt to Android:
Pulling Track Info From an Audio Stream Using PHP
http://www.smackfu.com/stuff/programming/shoutcast.html

Categories

Resources