Android how to record music from media player - android

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();
}
}
});

Related

Android download and play video file simultaneously by using videoView

I had start download file and start playing that file. If the file size is small (less than 15 MB). Following source download and play video perfectly.
If the file size is big (50 MB or more than that),Video playing getting started. For my case,File size is 50 MB,downloaded size is 10 MB and video view is played when the download is started, once the 10 MB size video is played,It waiting for the upcoming bytes. When it gets downloaded, audio only get played. Video frame is not get updated.
public class VideoDemo extends Activity {
private MediaController ctlr;
VideoView videoView = null;
Context context = null;
long totalRead = 0;
int bytesToRead = 50 * 1024;
private int mPlayerPosition;
private File mBufferFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
videoView = (VideoView) findViewById(R.id.videoview);
ctlr = new MediaController(this);
ctlr.setMediaPlayer(videoView);
videoView.setMediaController(ctlr);
videoView.requestFocus();
new GetYoutubeFile().start();
}
private class GetYoutubeFile extends Thread {
private String mUrl;
private String mFile;
public GetYoutubeFile() {
}
#Override
public void run() {
super.run();
try {
File bufferingDir = new File(
Environment.getExternalStorageDirectory()
+ "/YoutubeBuff");
InputStream stream = getAssets().open("famous.3gp");
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("test", "mp4");
System.out.println("hi");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
File bufferFile = File.createTempFile("test", "mp4");
BufferedOutputStream bufferOS = new BufferedOutputStream(
new FileOutputStream(bufferFile));
InputStream is = getAssets().open("famous.3gp");
BufferedInputStream bis = new BufferedInputStream(is, 2048);
byte[] buffer = new byte[16384];
int numRead;
boolean started = false;
while ((numRead = bis.read(buffer)) != -1) {
bufferOS.write(buffer, 0, numRead);
bufferOS.flush();
totalRead += numRead;
if (totalRead > 120000 && !started) {
Log.e("Player", "BufferHIT:StartPlay");
setSourceAndStartPlay(bufferFile);
started = true;
}
}
mBufferFile = bufferFile;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setSourceAndStartPlay(File bufferFile) {
try {
mPlayerPosition=videoView.getCurrentPosition();
videoView.setVideoPath(bufferFile.getAbsolutePath());
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onCompletion(MediaPlayer mp) {
mPlayerPosition = mp.getCurrentPosition();
try {
mp.reset();
videoView.setVideoPath(new File("mnt/sdcard/YoutubeBuff/"
+ mBufferFile).getAbsolutePath());
mp.seekTo(mPlayerPosition);
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Karthick
Your code seems ok!!
just register the OnCompletionListener,OnErrorListener to your VideoView.
videoView.setOnCompletionListener(this);
videoView.setOnErrorListener(this);
so once media player played the buffered stream it will goes to onCompletion or throws an error(Video Can't be played), Which can be handle by again changing seek position and playing through same buffered file.
(Please make sure that video bitrate and transfer rate needs to be equivalent) so buffering and streaming will run simultaneously.
implementations of methods could be like below,
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mPlayerErrorPos = mp.getCurrentPosition();
mPlayerPosition=mPlayerCompletionPos > mPlayerErrorPos ? mPlayerCompletionPos : mPlayerErrorPos;
try {
mp.reset();
videoView.setVideoPath(video.getAbsolutePath());
videoView.seekTo(mPlayerPosition);
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayerCompletionPos = mp.getCurrentPosition();
}

Concatenate two audio files and play resulting file

I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.

Call recorder is not working on android 4.1.2

Call Recorder is recording on most of the devices but not working on samsung grand. Means recording is started on incoming or outgoing and records the sound from the selected source (mic etc) but further device will stop to record the sound (could be the reason the recorder is not getting data from that source in in-call(Android's user privacy issue)).
I have tried AudioRecord and MediaRecorder for this but the problem remains unsolved.
private MediaRecorder recorder = null;
recorder.setAudioSource(1);
recorder.setOutputFormat(1);
recorder.setAudioEncoder(1);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
also i tried audiorecord but it is not working for this issue.
I will post a code for question.This code is working perfectly in my application
public void onStart(Intent intent, int startId) {
mSampleFile = null;
if (mSampleFile == null) {
String newFolder = "/Recording";
String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
try {
if (myNewFolder != null) {
mSampleFile = File.createTempFile(SAMPLE_PREFIX,
SAMPLE_EXTENSION, myNewFolder);
}
} catch (IOException e) {
}
}
if (mSampleFile != null) {
SharedPreferences mysharedprefs8 = getSharedPreferences(mypref32,
MODE_MULTI_PROCESS);
String status = mysharedprefs8.getString("pass", "AMR_NB");
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
if (status.equalsIgnoreCase("AMR")) {
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
} else if (status.equalsIgnoreCase("MPEG")) {
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
} else if (status.equalsIgnoreCase("3GPP")) {
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
} else {
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
}
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.setOutputFile(mSampleFile.getAbsolutePath());
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
mRecorder.setMaxDuration(600000);
try {
mRecorder.prepare();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mRecorder.start();
mRecorder.setOnInfoListener(new OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
try {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
} catch (Exception e) {
}
}
});
}

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

Saving android specific button sound

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();
}
}

Categories

Resources