Trouble converting mp3 to pcm in Kotlin/Android Studio - UnsupportedAudioFileException - android-studio

I've tried the following approaches:
mp3-to-wav-conversion-in-java
convert-mp3-to-pcm-in-java
Current Implementation:
...
var mp3URI = Uri.fromFile(file)
var mp3InputStream = this.contentResolver.openInputStream(mp3URI)
var byteArray = mp3InputStream!!.readBytes()
var pcmBytes = getAudioDataBytes(byteArray, AudioFormat(SAMPLE_RATE_HZ.toFloat(),16,1,true,false))
...
#Throws(UnsupportedAudioFileException::class, IllegalArgumentException::class, Exception::class)
fun getAudioDataBytes(sourceBytes: ByteArray?, audioFormat: AudioFormat?): ByteArray? {
require(!(sourceBytes == null || sourceBytes.size == 0 || audioFormat == null)) { "Illegal Argument passed to this method" }
var bais: ByteArrayInputStream? = null
var baos: ByteArrayOutputStream? = null
var sourceAIS: AudioInputStream? = null
var convert1AIS: AudioInputStream? = null
var convert2AIS: AudioInputStream? = null
return try {
bais = ByteArrayInputStream(sourceBytes)
sourceAIS = AudioSystem.getAudioInputStream(bais)
val sourceFormat: AudioFormat = sourceAIS.getFormat()
val convertFormat = AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.sampleRate,
16,
sourceFormat.channels,
sourceFormat.channels * 2,
sourceFormat.sampleRate,
false
)
convert1AIS = AudioSystem.getAudioInputStream(convertFormat, sourceAIS)
convert2AIS = AudioSystem.getAudioInputStream(audioFormat, convert1AIS)
baos = ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val readCount: Int = convert2AIS.read(buffer, 0, buffer.size)
if (readCount == -1) {
break
}
baos.write(buffer, 0, readCount)
}
baos.toByteArray()
} catch (uafe: UnsupportedAudioFileException) {
//uafe.printStackTrace();
throw uafe
} catch (ioe: IOException) {
//ioe.printStackTrace();
throw ioe
} catch (iae: IllegalArgumentException) {
//iae.printStackTrace();
throw iae
} catch (e: Exception) {
//e.printStackTrace();
throw e
} finally {
if (baos != null) {
try {
baos.close()
} catch (e: Exception) {
}
}
if (convert2AIS != null) {
try {
convert2AIS.close()
} catch (e: Exception) {
}
}
if (convert1AIS != null) {
try {
convert1AIS.close()
} catch (e: Exception) {
}
}
if (sourceAIS != null) {
try {
sourceAIS.close()
} catch (e: Exception) {
}
}
if (bais != null) {
try {
bais.close()
} catch (e: Exception) {
}
}
}
}
the approaches I've tried are giving me javax.sound.sampled.UnsupportedAudioFileException at the line
sourceAIS = AudioSystem.getAudioInputStream(bais)
I take it some of the .jar files need to be added to the run-time class-path. I figured putting the jar files in the libs folder and doing the gradle implementation was all that would be needed but apparently not. Where are the .jar files supposed to go so they are in the run-time class-path? Or if you have an easier way to convert an mp3 into pcm bytes I'd love to hear it.
Gradle dependancies:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation files('libs\\mp3plugin.jar')
implementation files('libs\\net.sourceforge.lame-3.98.4.jar')
implementation files('libs\\tritonus-share-0.3.7-2.jar')
implementation files('libs\\jl-1.0.1.jar')
implementation files('libs\\tritonus_mp3-0.3.6.jar')
implementation files('libs\\mp3spi-1.9.5-2.jar')
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

Turns out the jLayer libraby has a converter that some people find too slow but works fine for my purposes
var converter = Converter()
converter.convert(mp3File, wavFile)
From there just need to load the wav file, remove the wav header and fix the edieness

Related

define a constant instead of duplicating 5 times

I'm fairly new to Node.js and I am having some issues.
I received error in sonarqube as define a constant instead of duplicating 5 times for "-deleteFlag". how can i resolved this issue.
export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
if (typeof obj === "string") {
this["#text"] = obj;
this["-deleteFlag"] = "N";
} else {
try {
this["-deleteFlag"] = obj["-deleteFlag"];
} catch {
this["-deleteFlag"] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
}
export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
const deleteFlag = "-deleteFlag";
if (typeof obj === "string") {
this["#text"] = obj;
this[deleteFlag] = "N";
} else {
try {
this[deleteFlag] = obj[deleteFlag];
} catch {
this[deleteFlag] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
}
I think this should do the trick with SQ, at least when it comes to that particular variable. You can do the same with "#text" of course.
After edit: sorry my first answer was broken, I was in a rush and didn't realize what I was really writing down.
Given my updated snippet, you can do the following:
this[deleteFlag']: This will work.
this['-deleteFlag']: This will of course work but Sonar Qube will complain because your use of duplicated string literals.
this.deleteFlag: This won't work because would be looking for a deleteFlag key on the object. Such key doesn't exist, it's '-deleteFlag'.
this['deleteFlag']: this is functionally the same as the line above. Would look for a 'deletFlag' key on the object, which doesn't exist.
Sorry for the confusion! Hope this helps now

Get name of linux distribution running

Is there any way to get the linux distributionn name used to run a flutter app?
The only way I found is to parse the Platform.operatingSystemVersion string but I think if we can get it like so, Flutter team surely provide a proper way to do this?
By distribution name I mean Ubuntu, Fedora, Debian, etc.
First solution:
Found that device_info_plus_linux provide what I want.
To use it (without device_info_plus):
import 'package:device_info_plus_linux/device_info_plus_linux.dart';
import 'package:device_info_plus_platform_interface/device_info_plus_platform_interface.dart' show LinuxDeviceInfo;
[...]
LinuxDeviceInfo deviceInfoLinux = await DeviceInfoLinux().linuxInfo();
print('Linux distribution: ${deviceInfoLinux.id}');
deviceInfoLinux.id will return a string containing the name of the distribution in lowercase characters (ex: 'debian', 'ubuntu', ...). If the package don't found any id it will return 'linux'.
Second solution:
In my case doing work async was not possible so I implemented my own solution:
String _getLinuxDistribution() {
String linuxDistribution;
try {
final List<String> osEtc = File('/etc/os-release').readAsLinesSync();
linuxDistribution =
osEtc.firstWhere((element) => element.indexOf("ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(3).toLowerCase();
else
throw Exception;
} catch (e) {
try {
final List<String> osUsr = File('/usr/lib/os-release').readAsLinesSync();
linuxDistribution =
osUsr.firstWhere((element) => element.indexOf("ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(3).toLowerCase();
else
throw Exception;
} catch (e) {
try {
final List<String> lsb = File('/etc/lsb-release').readAsLinesSync();
linuxDistribution =
lsb.firstWhere((element) => element.indexOf("DISTRIB_ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(11).toLowerCase();
else
throw Exception;
} catch (e) {
print(_red("Error getting Linux distribution name"));
linuxDistribution = 'linux';
}
}
}
return linuxDistribution;
}
note that the performance impact is negligable, I mesured it between 10ms and 30ms.

C++/CLI code doesn't enter .then part of the create_task function

This is the code that I have:
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
XTRACE(L"=========================================will start onNavigated ");
auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
m_mediaCaptureMgr = mediaCapture;
IAsyncAction ^asyncAction = m_mediaCaptureMgr->InitializeAsync();
try
{
create_task(asyncAction).then([this](task<void> initTask)
{
XTRACE(L"=========================================will start onNavigated 2");
try
{
initTask.get();
auto mediaCapture = m_mediaCaptureMgr.Get();
if (mediaCapture->MediaCaptureSettings->VideoDeviceId != nullptr && mediaCapture->MediaCaptureSettings->AudioDeviceId != nullptr)
{
String ^fileName;
fileName = VIDEO_FILE_NAME;
XTRACE(L"=================================Device initialized successful\n");
create_task(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName))
.then([this](task<StorageFile^> fileTask)
{
XTRACE(L"=================================Create record file successful\n");
m_recordStorageFile = fileTask.get();
MediaEncodingProfile^ recordProfile = nullptr;
recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
stream = ref new InMemoryRandomAccessStream();
return m_mediaCaptureMgr->StartRecordToStreamAsync(recordProfile, stream);
}).then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Start Record successful\n");
}
catch (Exception ^e)
{
XTRACE(L"======ERRROR is : %d", e);
}
});
}
else
{
XTRACE(L"=================================No VideoDevice/AudioDevice Found\n");
}
XTRACE(L"=================================WILL EXIT \n");
}
catch (Exception ^ e)
{
XTRACE(L"============================================ERROR IS: %d\n", e);
}
}
);
}
catch (Exception ^ e)
{
XTRACE(L"============================================before create task ERROR IS: %d\n", e);
}
XTRACE(L"=================================SLEEP 20000====================================\n");
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
XTRACE(L"=================================TIME ENDED====================================\n");
// stop device detection
try
{
XTRACE(L"=================================Stopping Record\n");
create_task(m_mediaCaptureMgr->StopRecordAsync())
.then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Stop record successful: %d\n", stream->Size);
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR while stoping 2: %d\n", e);
}
});
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR try catch 3 stoping: %d\n", e);
}
CloseHandle(ghEvent);
// destruct the device manager
XTRACE(L"=====================================================================END\n");
}
In the log I see:
=========================================will start onNavigated
And then directly:
=====================================================================
=================================SLEEP 20000====================================
What is strange is that I had this code in a unittest and it worked, I created a new windows phone project with a UI and it doesn't work
Apparently it was because of the ThreadSleep:
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
In the library project where I was working I was using a different sleep, provided by the library, and that would work. So this was the line that would cause the application to block itself.
I worked my way around this by including 2 buttons in the app, for the start and stop recording.

platformRequest not working in J2ME

I'm triyng to play .mp3 file using platformRequest(). I verified the file path and it is correct. And I'm using Nokia 210 for testing. Please help me to fix this issue.
try {
platformRequest("file:///C:/song.mp3");
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
I know you have already verified whether there is file or not. though check my below code once and post comment with results.
Added -
public boolean isFileExisted(String path) {
boolean isExisted = false;
FileConnection filecon = null;
try {
filecon = (FileConnection) Connector.open(path, Connector.READ);
isExisted = filecon.exists();
} catch (java.lang.SecurityException e) {
} catch (Exception e) {
} finally {
try {
if (filecon != null) {
filecon.close();
}
catch (Exception e) {
}
}
return isExisted;
}
}
public void playFileFromSDCard() {
String path1 = "file:///C:/song.mp3";
String path2 = "file:///E:/song.mp3";
if (isFileExisted(path1)) {
try {
System.out.println("path1 exist -> calling platform request " + path1);
platformRequest(path1);
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
}
else if (isFileExisted(path2)) {
try {
System.out.println("path2 exist -> calling platform request " + path2);
platformRequest(path2);
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
}
else {
System.out.println("both path doesnt exists");
}
}
After so many searches i found some reasons for the issue. This may help for people in future who is having the same problem. refer the following links.
Open file with MIDlet.platformRequest() ,
How to play media file in System media player in j2me????

Getting code from all (closed) files in solution in Visual Studio SDK

I'm trying to get and edit the code of all the html-files in the project
i found a way to loop over all ProjectItems
IEnumerator Projects = _applicationObject.Solution.Projects.GetEnumerator();
while (Projects.MoveNext())
{
IEnumerator Items = ((Project)Projects.Current).ProjectItems.GetEnumerator();
Queue<ProjectItem> ProjectItems = new Queue<ProjectItem>();
while (Items.MoveNext())
{
ProjectItem SubItem = (ProjectItem)Items.Current;
try
{
if (SubItem.Document != null) DocumentIndex.Add(SubItem.Document);
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
ProjectItems.Enqueue(SubItem);
}
//follow the tree down
while (ProjectItems.Count != 0)
{
ProjectItem ProjectItem = ProjectItems.Dequeue();
if (ProjectItem.ProjectItems != null)
{
foreach (ProjectItem SubItem in ProjectItem.ProjectItems)
{
ProjectItems.Enqueue(SubItem);
try
{
try
{
SubItem.Open(SubItem.Kind);
DocumentIndex.Add(SubItem.Document);
}catch(Exception Ex){
Console.WriteLine(Ex.Message);
}
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
}
}
}
}
now i can't get to the code of the files that are not open in an editor window.
how do i get and edit the code of "not opened" projectItems?
how do i detect if a file is a code file? (eg: .cs, .html, .htm, .asp, ....
You must open the ProjectItem that you want to read or edit
DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
var project = dte.Solution.Projects.Item(1);
var projectItems = project.ProjectItems;
var anyItem = projectItems.Item(0);
Window anyItemWindow = anyItem.open()
var selection = anyItem.Document.Selection as TextSelection;
selection.SelectAll();
Console.WriteLine(selection.Text) // All code
anyItem.Document.Close() //Close Document
if you don't open the ProjectItem anyItem.Doument is null.
Note: selection.Insert("") can be used to change the code

Resources