Video Decryption Issue In Android - java

I am using "AES" algorithm for Decryption of video, Which is stored on External Sd card in Encrypted format.While decrypting video its decrypt only 47% and get stop. please give solution
public void createDecryptedFile(File decryptedFileDir, File decryptedFile,
File encryptedFile) {
try {
if (!decryptedFileDir.exists()) {
decryptedFileDir.mkdirs();
}
Cipher decipher;
decryptedFile.createNewFile();
deleteFile = decryptedFile;
FileInputStream encryptedFileInputstream = new FileInputStream(
encryptedFile);
FileOutputStream decryptedFileOutputstream = new FileOutputStream(
decryptedFile);
decipher = Cipher.getInstance("AES");
Key key = generateKey();
decipher.init(Cipher.DECRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(
decryptedFileOutputstream, decipher);
byte data[] = new byte[10000 * 1024];
int count;
try {
while ((count = encryptedFileInputstream.read(data)) != -1 && !stopConversion) {
Log.d("#########", "##########");
total += count;
Log.e("convert count", total + "");
cos.write(data, 0, count);
final long l = encryptedFile.length();
runOnUiThread(new Runnable() {
public void run() {
// Show percentage
loadingpercent.setText("" + (int) (total * 100 / l) + "%");
}
});
Log.d("$$$$$$$$",""+encryptedFileInputstream.read(data));
}

Replace :-
CipherInputStream cis = new CipherInputStream(encryptedFileInputstream, cipher);
int count;
try {
int b;
byte[] d = new byte[10000 * 2048];
while ((b = cis.read(d)) != -1 && !stopConversion) {
total += b;
final long l = encryptedFile.length();
decryptedFileOutputstream.write(d, 0, b);
runOnUiThread(new Runnable() {
public void run() {
loadingpercent.setText("" + (int) (total * 100 / l) + "%");
}
});
}

Related

Split wav files based on Silence in Java

I want to split wav files in to number of waves files, each of them
is split
by silence between words, I tried to code a bit. I managed to split the files
But things got complex when trying to dedect silence.. any help?
Thanks
Splits WAV-files in multiple parts. This class splits a big WAV-file in
multiple WAV-file, each with a fixed length (SPLIT_FILE_LENGTH_MS). It
takes
it input file from an embedded resource, and writes a series of out*.wav files.
heres my code so far:
public class WaveSplitter {
public static int SPLIT_FILE_LENGTH_MS = 0;
public static final String INPUT_FILE_LOCATION = "resources/AUD-20171027-WA0001.wav";
public static void main(String[] args) {
try {
// Get the wave file from the embedded resources
URL defaultImage =
WaveSplitter.class.getResource(INPUT_FILE_LOCATION);
// GSpeechDuplex duplex = new
// GSpeechDuplex("AIzaSyDHQsnCHDk71x-Dpp05IIK3tYNOEP84z1s");
// duplex.setLanguage("heb");
File audioFile = new File(defaultImage.toURI());
File soundFile = new File(defaultImage.toURI());
FileInputStream fileInputStream = null;
long duration = 0;
try {
fileInputStream = new FileInputStream(soundFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
duration =
Objects.requireNonNull(fileInputStream).getChannel().size() / 128;
} catch (IOException e) {
}
AudioInputStream stream;
WavFile wavFile = WavFile.openWavFile(new File(defaultImage.toURI()));
AudioInputStream audioInputStream =
AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = audioInputStream.getFormat();
long frames = audioInputStream.getFrameLength();
double durationInSeconds = (frames + 0.0) / format.getFrameRate();
System.out.println("Duration " + durationInSeconds + " seconds \n");
durationInSeconds = durationInSeconds * 1000;
SPLIT_FILE_LENGTH_MS = (int) durationInSeconds;
// wavFile.display();
// Get the number of audio channels in the wav file
int numberChannels = wavFile.getNumChannels();
System.out.println("number channels is " + numberChannels);
System.out.println("SPLIT_FILE_LENGTH_MS is " + SPLIT_FILE_LENGTH_MS);
int framesRead;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
byte[] bytes = FileUtils.readFileToByteArray(soundFile);
// String encoded = Base64.encodeToString(bytes, 0);
// playSoundFile(soundFile);
WavFile inputWavFile = WavFile.openWavFile(soundFile);
// File audioFile = new File("AUD-20171027-WA0001.wav");
// sendToGoogleViaOnvegoServer(myByteData);
/// System.out.println("Seneteces:\n " + bytes);
// Get the number of audio channels in the wav file
int numChannels = inputWavFile.getNumChannels();
// set the maximum number of frames for a target file,
// based on the number of milliseconds assigned for each file
int maxFramesPerFile = (int) inputWavFile.getSampleRate() *
SPLIT_FILE_LENGTH_MS / 1000;
System.out.println("maxFramesPerFile is " + maxFramesPerFile + "\n");
// Create a buffer of maxFramesPerFile frames
double[] buffer = new double[maxFramesPerFile * numChannels];
// sendToGoogleViaOnvegoServer(myByteData);
framesRead = inputWavFile.readFrames(buffer, maxFramesPerFile);
// System.out.print(buffer.length);
int fileCount = 0;
int s = 0;
int j = 0;
int timercount = 0;
int audiorecord = 0;
int count = 0;
// SPLIT_FILE_LENGTH_MS = 0;
double maxlengh = framesRead * numChannels;
System.out.print("Audio Duration " + maxFramesPerFile + "\n");
int arraylengh = framesRead * numChannels;
System.out.print("frame*channels " + framesRead * numChannels);
///loop to find silent places
do {
// Read frames into buffer
framesRead = inputWavFile.readFrames(buffer, maxFramesPerFile);
// System.out.print(framesRead);
for (s = 0; s < arraylengh; s++) {
if (buffer[s] == 0) {
// System.out.print(s + ", " + buffer[s] + "\n");
count++;
timercount++;
}
else {
for (j = s; j < arraylengh; j++) {
if (buffer[j] != 0)
{
} else {
SPLIT_FILE_LENGTH_MS = 1500;
maxFramesPerFile = (int)
inputWavFile.getSampleRate() * SPLIT_FILE_LENGTH_MS /
1000;
framesRead = inputWavFile.readFrames(buffer,
maxFramesPerFile);
// framesRead = inputWavFile.readFrames(buffer,
maxFramesPerFile);
WavFile outputWavFile = WavFile.newWavFile(new
File("out" + (fileCount + 1) + ".wav"),
inputWavFile.getNumChannels(), framesRead,
inputWavFile.getValidBits(),
inputWavFile.getSampleRate());
// Write the buffer
outputWavFile.writeFrames(buffer, framesRead);
outputWavFile.close();
return;
}
}
}
// System.out.print(maxFramesPerFile);
}
// SPLIT_FILE_LENGTH_MS=1000;
maxFramesPerFile = (int) inputWavFile.getSampleRate() *
SPLIT_FILE_LENGTH_MS / 1000;
framesRead = inputWavFile.readFrames(buffer, maxFramesPerFile);
WavFile outputWavFile = WavFile.newWavFile(new File("out" + (
fileCount + 1) + ".wav"),
inputWavFile.getNumChannels(), framesRead,
inputWavFile.getValidBits(),
inputWavFile.getSampleRate());
// Write the buffer
outputWavFile.writeFrames(buffer, framesRead);
outputWavFile.close();
fileCount++;
// System.out.print(fileCount);
} while (framesRead != 0);
System.out.print(count + "\n");
System.out.print(fileCount);
//catch error
} catch (Exception e) {
System.err.println(e);
}
}
// Play sound function
public static void playSoundFile(File soundFile)
throws UnsupportedAudioFileException, IOException, LineUnavailableException {
try {
final Clip clip = (Clip) AudioSystem.getLine(new Info(Clip.class));
clip.removeLineListener(new LineListener() {
#Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
clip.open(AudioSystem.getAudioInputStream(soundFile));
clip.start();
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}

Potential use for data that contains its own hash?

I was writing some code to simulate the proof-of-work done by the Bitcoin network while generating blocks when I suddenly became curious: How can you create a datum that contains it's own hash?
Just for fun, I wrote a program that attempts to create data that contains it's own hash. 4 random bytes are generated, then a nonce is added at the end and the whole value is hashed with CRC32. The nonce in incremented and the process repeats until the program finds a hash that matches the original 4 bytes.
Note: The nonce can increase indefinitely.
Here's an example of the output after approx 1,980,000,000 attempts:
Found a match!
Data: 7a73a2d4ab833876
Original hash: 7a73a2d4 new hash: 7a73a2d4
Is there a potential use for this?
package selfhash;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
*
* #author dylan
*/
public class SelfHash {
static byte[] data;
static byte[] hash = new byte[4];
public static void main(String[] args) {
// TODO code application logic here
SecureRandom random = new SecureRandom();
random.nextBytes(hash);
data = new byte[hash.length + 1];
System.arraycopy(hash, 0, data, 0, hash.length);
long c = 0;
while (true) {
recalculateData();
byte[] dataHash = crc32AsByteArray(data);
if (c % 10000000 == 0) {
System.out.println("Calculated " + c + " hashes");
System.out.println("Data: " + byteArrayToHex(data));
System.out.println("Original hash: " + byteArrayToHex(hash) + " new hash: " + byteArrayToHex(dataHash));
}
if (Arrays.equals(hash, dataHash)) {
System.out.println("Found a match!");
System.out.println("Data: " + byteArrayToHex(data));
System.out.println("Original hash: " + byteArrayToHex(hash) + " new hash: " + byteArrayToHex(dataHash));
break;
}
c++;
}
}
public static void recalculateData() {
int position = hash.length;
while (true) {
int valueAtPosition = unsignedToBytes(data[position]);
if (valueAtPosition == 255) {
//increase size of data
if (position == data.length-1) {
byte[] newData = new byte[data.length + 1];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
data[position] = (byte) (0);
position++;
} else {
data[position] = (byte) (valueAtPosition + 1);
break;
}
}
}
public static byte[] hexToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
private static final char[] BYTE2HEX = ("000102030405060708090A0B0C0D0E0F"
+ "101112131415161718191A1B1C1D1E1F"
+ "202122232425262728292A2B2C2D2E2F"
+ "303132333435363738393A3B3C3D3E3F"
+ "404142434445464748494A4B4C4D4E4F"
+ "505152535455565758595A5B5C5D5E5F"
+ "606162636465666768696A6B6C6D6E6F"
+ "707172737475767778797A7B7C7D7E7F"
+ "808182838485868788898A8B8C8D8E8F"
+ "909192939495969798999A9B9C9D9E9F"
+ "A0A1A2A3A4A5A6A7A8A9AAABACADAEAF"
+ "B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF"
+ "C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"
+ "D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"
+ "E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF"
+ "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF").toLowerCase().toCharArray();
;
public static String byteArrayToHex(byte[] bytes) {
final int len = bytes.length;
final char[] chars = new char[len << 1];
int hexIndex;
int idx = 0;
int ofs = 0;
while (ofs < len) {
hexIndex = (bytes[ofs++] & 0xFF) << 1;
chars[idx++] = BYTE2HEX[hexIndex++];
chars[idx++] = BYTE2HEX[hexIndex];
}
return new String(chars);
}
public static String sha256AsHexString(byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return byteArrayToHex(digest.digest(bytes));
} catch (Exception e) {
throw new Error(e);
}
}
public static byte[] sha256AsByteArray(byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(bytes);
} catch (Exception e) {
throw new Error(e);
}
}
public static byte[] crc32AsByteArray(byte[] bytes) {
Checksum checksum = new CRC32();
checksum.update(bytes, 0, bytes.length);
long value = checksum.getValue();
byte[] resultExcess = ByteBuffer.allocate(8).putLong(value).array();
byte[] result = new byte[4];
System.arraycopy(resultExcess, 4, result, 0, 4);
return result;
}
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
}
I can't think of a use.
CRC's are linear, and so the equations can be solved very fast to get the second four bytes. You don't need two billion trials to find it. See spoof.c.

Encrypt and Decrypt files

I need to download mp3 files, encrypt, when necessary, to decrypt a temporary mp3 and listen.
Used as reference this answer already done in StackOverflow
Encrypting files with AES on Android
All steps works. But when I send the generated mp3 file for the MediaPlayer does not recognize and break.
These are my download and encryption method
public void executeAsyncDownload(String urlFile, String id, int position, HandlerCallback callback) {
String encryptedName = Cypher.md5(id);
if (MediaUtils.containsFile(encryptedName)) {
callback.onDownloadFinish(position);
return;
}
File dir = MediaUtils.getDestinationFolder(destination);
if (!dir.exists()) {
dir.mkdir();
}
try {
if (canceled)
return;
callback.onDownloadStart(position);
URL url = new URL(urlFile);
URLConnection connection = url.openConnection();
connection.connect();
int tamFile = connection.getContentLength();
String filePath = MediaUtils.getFilePath(MediaUtils.tempPath + encryptedName).toString();
InputStream fis = new BufferedInputStream(url.openStream());
OutputStream fos = new FileOutputStream(filePath);
File file = new File(filePath);
byte data[] = new byte[80192];
int count;
long total = 0;
while ((count = fis.read(data)) != -1) {
total += count;
if (tamFile > 0) {
int percentage = (int) (total * 100 / tamFile);
if (percentage % 20 == 0)
callback.onDownloadProgress(percentage, position);
}
fos.write(data, 0, count);
if (canceled) {
MediaUtils.deleteFile(file);
return;
}
}
if (canceled)
return;
byte[] key = (salt + cryptPassword).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 8);
SecretKeySpec sks = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8192];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
outputEncrypted.write(d);
outputEncrypted.close();
fos.flush();
fos.close();
fis.close();
MediaUtils.deleteFile(file);//delete temp file
callback.onDownloadFinish(position);
} catch (Exception e) {
e.printStackTrace();
callback.onDownloadError(position);
}
}
This are my decryption method
#SafeVarargs
#Override
protected final File doInBackground(HashMap<String, Object>... params) {
String path = (String) params[0].get(FILE_PATH);
String fileName = String.valueOf(params[0].get(FILE_NAME));
boolean encrypted = (boolean) params[0].get(ENCRYPTED);
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + path + File.separator);
File file;
if (!encrypted) {
file = new File(dir + File.separator + fileName);
return file;
}
file = new File(dir + File.separator + Cypher.md5(fileName));
File tempMp3 = null;
try {
tempMp3 = File.createTempFile(TEMP, MP3, context.getCacheDir());
tempMp3.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream(file);
byte[] key = (DownloadManager.salt + DownloadManager.cryptPassword).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 8);
SecretKeySpec sks = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(tempMp3);
int b;
byte[] d = new byte[80192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return tempMp3;
}
You seem to have a typo in either your encrypt or decrypt method.
In encryption:
int b;
byte[] d = new byte[8192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
In decryption:
int b;
byte[] d = new byte[80192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
The byte array d in decryption is about 10x larger than the byte array in encryption.
After doing this:
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8192];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
outputEncrypted.write(d);
outputEncrypted.close();
the outputEncrypted file will just contain the last buffer full of data. Furthermore, this data will not be encrypted.

Play a WAV File Mulitple Times Through AudioTrack

I am making a metronome app that uses AudioTrack to play different sounds for different instruments. I want to use a .wav file that I have of one hit on a cowbell for one of the options. I can get the first cowbell hit to work but then it doesn't play any after that.
MainActivity.java
metronome.playInstrumental(getResources().openRawResource(R.raw.cowbell));
Metronome.java
public Metronome(Handler handler) {
audioGenerator.createPlayer();
this.mHandler = handler;
}
public void calcSilence() {
silence = (int) (((60 / bpm) * 8000) - tick);
soundTickArray = new double[this.tick];
soundTockArray = new double[this.tick];
silenceSoundArray = new double[this.silence];
double[] tick = audioGenerator.getSineWave(this.tick, 8000, beatSound);
double[] tock = audioGenerator.getSineWave(this.tick, 8000, electronicSound);
for(int i = 0; i < this.tick; i++) {
soundTickArray[i] = tick[i];
soundTockArray[i] = tock[i];
}
for(int i = 0; i < silence; i++)
silenceSoundArray[i] = 0;
}
public void playInstrumental(InputStream inputStream) {
calcSilence();
do {
msg = new Message();
msg.obj = ""+currentBeat;
audioGenerator.playSound(inputStream);
mHandler.sendMessage(msg);
audioGenerator.writeSound(silenceSoundArray);
} while(play);
}
AudioGenerator.java
public class AudioGenerator {
private int sampleRate;
private AudioTrack audioTrack;
public AudioGenerator(int sampleRate) {
this.sampleRate = sampleRate;
}
public double[] getSineWave(int samples, int sampleRate, double frequencyOfTone){
double[] sample = new double[samples];
for (int i = 0; i < samples; i++) {
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / frequencyOfTone));
}
return sample;
}
public byte[] get16BitPcm(double[] samples) {
byte[] generatedSound = new byte[2 * samples.length];
int index = 0;
for (double sample : samples) {
// scale to maximum amplitude
short maxSample = (short) ((sample * Short.MAX_VALUE));
// in 16 bit wav PCM, first byte is the low order byte
generatedSound[index++] = (byte) (maxSample & 0x00ff);
generatedSound[index++] = (byte) ((maxSample & 0xff00) >>> 8);
}
return generatedSound;
}
public void createPlayer(){
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, sampleRate,
AudioTrack.MODE_STREAM);
audioTrack.play();
}
public void writeSound(double[] samples) {
byte[] generatedSnd = get16BitPcm(samples);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
}
public void destroyAudioTrack() {
audioTrack.stop();
audioTrack.release();
}
public void playSound(InputStream inputStream) {
int i = 0;
int bufferSize = 512;
byte [] buffer = new byte[bufferSize];
try {
while((i = inputStream.read(buffer)) != -1) {
audioTrack.write(buffer, 0, i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I was able to get it to work using this:
public void playSound(InputStream inputStream) {
int bufferSize = 512;
byte[] buffer = new byte[bufferSize];
i = 0;
try {
while((i = inputStream.read(buffer)) > -1) {
audioTrack.write(buffer, 0, i);
}
inputStream.reset();
} catch (IOException e) {
e.printStackTrace();
}
}

Decode mp3 to pcm, and play with audiotrack in Google Android

First of all, if not using function decode_path , I can play .wav file with my code , and it works fine I use Jlayer and audio track to play the song.
Second, if I use function decode_path it can decode mp3 to pcm file , and pass the byte[] to function PlayAudioTrack, and let it play.
The quesion is,I don't know where my code is wrong , I use 320Kbps, 44.1Khz stereo type, Layer3 mp3, but the AudioTrack plays noise but no music~!!!!
can anyone ?
???
My code
public void PlayAudioTrack(String filePath) throws IOException{
int intSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
//Reading the file..
int count = 512 * 1024; // 512 kb
// byte[] byteData = null;
// byteData = new byte[(int)count];
//we can decode correct byte data here
byte[] byteData = null;
byteData = decode_path(filePath, 0, 20000);
File file = null;
file = new File(filePath);
FileInputStream in = null;
try {
in = new FileInputStream( file );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int bytesread = 0, ret = 0;
int size = (int) file.length();
at.play();
while (bytesread < size) {
Log.e("devon","write byte array with sizes");
ret = in.read( byteData,0, count);
if (ret != -1) {
Log.e("devon","Write the byte array to the track");
at.write(byteData,0, ret);
bytesread += ret;
}else break;
}
at.stop();
at.release();
}
public static byte[] decode_path(String path, int startMs, int maxMs)
throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
float totalMs = 0;
boolean seeking = true;
File file = new File(path);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 8 * 1024);
try {
Bitstream bitstream = new Bitstream(inputStream);
Decoder decoder = new Decoder();
boolean done = false;
while (! done) {
Header frameHeader = bitstream.readFrame();
if (frameHeader == null) {
done = true;
} else {
totalMs += frameHeader.ms_per_frame();
if (totalMs >= startMs) {
seeking = false;
}
if (! seeking) {
SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);
if (output.getSampleFrequency() != 44100
|| output.getChannelCount() != 2) {
throw new IllegalArgumentException("mono or non-44100 MP3 not supported");
}
short[] pcm = output.getBuffer();
for (short s : pcm) {
outStream.write(s & 0xff);
outStream.write((s >> 8 ) & 0xff);
}
}
if (totalMs >= (startMs + maxMs)) {
done = true;
}
}
bitstream.closeFrame();
}
return outStream.toByteArray();
} catch (BitstreamException e) {
throw new IOException("Bitstream error: " + e);
} catch (DecoderException e) {
Log.w(TAG, "Decoder error", e);
throw new IOException("Decoder error: " + e);
}
}
public void PlayAudioTrack(String filePath) throws IOException{
int intSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
//Reading the file..
int count = 512 * 1024; // 512 kb
// byte[] byteData = null;
// byteData = new byte[(int)count];
//we can decode correct byte data here
byte[] byteData = null;
byteData = decode_path(filePath, 0, 20000);
int temp =0;
at.play();
while (temp<byteData.length)
{
at.write(byteData, temp, count);
temp+= count;
}
at.stop();
at.release();
}

Categories

Resources