How to play Base64 encoded audio in android? - android

What I have tried till now :-
Have a Base64 encoded String of an audio file.
Now here I am trying to play like this.
public void PlayAudio(String base64EncodedString){
try
{
String url = "data:audio/mp3;base64,"+base64EncodedString;
Uri uri = Uri.parse(url);
mediaPlayer.setDataSource(MainActivity.this, uri);
/*mediaPlayer.prepare();*/
mediaPlayer.start();
}
catch(Exception ex){
System.out.print(ex.getMessage());
}
}
and
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// resetting mediaplayer instance to evade problems
mediaPlayer.reset();
// In case you run into issues with threading consider new instance like:
// MediaPlayer mediaPlayer = new MediaPlayer();
// Tried passing path directly, but kept getting
// "Prepare failed.: status=0x1"
// so using file descriptor instead
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
//mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
But audio is not playing.
May any one assist me over this.

You actually need to decode the Base64 encoded String before you play it. Please check the decoding procedure here

Related

Get inverse of bytes for audio that it becomes phase out of original audio signal

I want eliminate audio by playing original audio and its inverse at the same time. I have the byte array of the audio but I cannot find a way to take inverse of that byte array. I want to shift the phase to 180. So that it becomes inverse of the original signal. Hence silence.
I followed this link https://www.tutorialspoint.com/android/android_audio_capture.htm to record audio. To convert audio to bytes I followed How to convert video/audio file to byte array and vice versa in android.? this question. And the best answer to this question Android - Playing mp3 from byte[] to play the bytes. I followed http://programminglinuxblog.blogspot.com/2014/07/how-to-flip-all-bits-in-bytearray-java.html link to get inverse. But when I play audio with only the inverse bytes nothing plays.
byte[] toFlip, flipped;
try {
toFlip = convertAudioToBytes();
BitSet set = BitSet.valueOf(toFlip);
set.flip(0, set.length());
flipped = set.toByteArray();
Toast.makeText(MainActivity.this, "Inveresed Successfully", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Inveresed Failed" + e, Toast.LENGTH_LONG).show();
System.out.println("Inveresed Failed" + e);
}
public byte[] convertAudioToBytes() throws IOException {
FileInputStream fis = new FileInputStream(AudioSavePathInDevice);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// resetting mediaplayer instance to evade problems
mediaPlayer.reset();
// In case you run into issues with threading consider new instance like:
// MediaPlayer mediaPlayer = new MediaPlayer();
// Tried passing path directly, but kept getting
// "Prepare failed.: status=0x1"
// so using file descriptor instead
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
It should play the inverse when flipped byte array is played. But nothing plays.

Pass local video to mediametadataretriever throws IllegalArgumentException

In my android app I want to extract video frames. I am using MediaMetaDataRetriever for the same.
How I set datasource
Log.d("DEBUG", videoPathUri.getPath());
metadataRetriever.setDataSource(mContext, videoPathUri);
Here is the log output
/storage/emulated/0/Android/data/com.live.hootout/files/HootVideos/10701.mp4
How can I load video stored in android data folder into mediametadataretriever?
Try this...
File file = new File(context.getDataDir(),filename);
Here is how I did it.
File file = new File(videoPathUri.getPath());
try {
FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
metadataRetriever.setDataSource(inputStream.getFD());
}catch(FileNotFoundException e){
Log.d("DEBUG", "FileNotFoundException", e);
}catch(IOException ea){
Log.d("DEBUG", "IOException", ea);
}

Is there any way to copy byte by byte from a file and play it using videoView in android?

I have tried this but it's not working. It copies all the bytes at once and play it. But i want to copy byte by byte from a file and play this video during/while receiving...
Some Code
tempFile = new File(Environment.getExternalStorageDirectory()+ "/" +"temp.mp4");
int length=0;
byte[] vidBytes = new byte[(int) file.length()];
try {
//while (length<100)
//{
fileInputStream = new FileInputStream(file);
fileInputStream.read(vidBytes,0,vidBytes.length);
fileInputStream.close();
videoPlayer.setVideoPath(tempFile.getAbsolutePath());
Toast.makeText(this,tempFile.getPath(),Toast.LENGTH_LONG).show();
videoPlayer.start();
length++;
//}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
fileOutputStream.write(vidBytes,0,50,vidBytes.length);
fileOutputStream.close();
what the hell are you doing? the fileInputStream is practically useless ! you read the bytes into the byte array vidBytes, but never actually use it anywhere, videoView doesn't require you to open an input stream, all videoView requires is the path to the file and the videoView code takes care of opening the stream and loading the data efficiently.
Also why are you writing the same Byte array that you read just few statements ago not modify it and write it back to the SAME FILE!? What are you trying to accomplish here?
P.S This is all you need to do to play the mp4 file in the videoview
tempFile = new File(Environment.getExternalStorageDirectory()+ "/" +"temp.mp4");
videoPlayer.setVideoPath(tempFile.getAbsolutePath());
Toast.makeText(this,tempFile.getPath(),Toast.LENGTH_LONG).show();
videoPlayer.start();

Saving ByteArray of audio into an Audio File

I'm working on a test app to integrate soundtouch (an open source audio processing library) on Android.
My test app already can receive input from the mic, pass the audio thru soundtouch and output the processed audio to an AudioTrack instance.
My question is, how can I change the output from AudioTrack to a new File on my device?
Here's the relevant code in my app (where I'm processing the output of soundtouch, into the input for AudioTrack)
// the following code is a stripped down version of my code
// in no way its supposed to compile or work. Its here for reference purposes
// pre-conditions
// parameters - input : byte[]
soundTouchJNIInstance.putButes(input);
int bytesReceived = soundTouchJNIInstance.getBytes(input);
audioTrackInstance.write(input, 0, bytesReceived);
Any ideas on how to approach this problem? Thanks!
Hope you are already getting the input voice from microphone and saved on a file.
Firstly, import JNI libraries to your oncreate method :
System.loadLibrary("soundtouch");
System.loadLibrary("soundstretch");
Soundstrech library :
public class AndroidJNI extends SoundStretch{
public final static SoundStretch soundStretch = new SoundStretch();
}
Now you need to call soundstrech.process with the input file path and the desired output file to store processed voice as parameters :
AndroidJNI.soundStretch.process(dataPath + "inputFile.wav", dataPath + "outputFile.wav", tempo, pitch, rate);
File sound = new File(dataPath + "outputFile.wav");
File sound2 = new File(dataPath + "inputFile.wav");
Uri soundUri = Uri.fromFile(sound);
The soundUri can be provided as a source to media player for play back :
MediaPlayer mediaPlayer = MediaPlayer.create(this, soundUri);
mediaPlayer.start();
Also note that, the sample size for recording should be selected dynamically by declaring an Array of Sample Rates :
int[] sampleRates = { 44100, 22050, 11025, 8000 }
The best way to write byteArray this :
public void writeToFile(byte[] array)
{
try
{
String path = "Your path.mp3";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
I am not aware of sound touch at all and the link i am providing no where deals with jni code, but you can have a look at it if it helps you any way: http://i-liger.com/article/android-wav-audio-recording
I think the best way to achieve this is converting that audio to a byte[] array. Assuming you have already done that (if not, comment it and I'll provide an example), the above code should work. This assumes you're saving it in a external sdcard in a new directory called AudioRecording and saving it as audiofile.mp3.
final File soundFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "AudioRecording/");
soundFile.mkdirs();
final File outFile = new File(soundFile, 'audiofile.mp3');
try {
final FileOutputStream output = new FileOutputStream(outFile);
output.write(yourByteArrayWithYourAudioFileConverted);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mkdirs() method will try to construct all the parent directories if they're missing. So if you're planning to store in a 2 or more level depth directory, this will create all the structure.
I use a simple test code snippet to write my audio byte arrays:
public void saveAudio(byte[] array, string pathAndName)
{
FileOutputStream stream = new FileOutputStream(pathAndName);
try {
stream.write(array);
} finally {
stream.close();
}
}
You will probably need to add some exception handling if you are going to be using this in a production environment, but I utilise the above to save audio whenever I am am in the development phase or for personal non-release projects.
Addendum
After some brief thought I have changed my snippet to the following slightly more robust format:
public void saveAudio(byte[] array, string pathAndName)
{
try (FileOutputStream stream= new FileOutputStream(pathAndName)) {
stream.write(array);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
stream.close();
}
}
You can use the method using SequenceInputStream, in my app I just merge 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();
}
}
}

How to download and play the song(.mp3,.m4a) if we know the url in android

I need to download a .mp3 or .m4a file from the server by using an URL, and then play that song.
Any ideas?
Try this code in your file:
USE
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();
like this.
Hope this will help you a lot.
There are plenty of questions of how to download a file in android. Just search.
On the other hand, you can use android's MediaPlayer to play the file from the internet without downloading it.

Categories

Resources