How to identify AudioEncoding and SampleRateHertz of an audio file - java

I am working on Google cloud Speech-to-text samples.
I took a sample from from this link GoogleCloudPlatform speech to text sample
And I referred Quickstart: Using Client Libraries
Sample files given in that example works fine. It gives text of that audio file.
But If I give my own audio file, it does not returns anything.
Cloud request includes audio file, AudioEncoding and SampleRateHertz.
Issue may be in AudioEncoding and SampleRateHertz of my own audio file.
How to identify AudioEncoding and SampleRateHertz of an audio file?

AudioEncoding's Java enum has the following possible values:
AudioEncoding.AMR -> .awb/.3gp files
AudioEncoding.AMR_WB -> .awb/.3gp files
AudioEncoding.FLAC -> .flac files
AudioEncoding.LINEAR16 -> .wav files
AudioEncoding.MULAW -> .wav files
AudioEncoding.OGG_OPUS -> .ogg/.opus files
AudioEncoding.SPEEX_WITH_HEADER_BYTE -> no clue, maybe .speex
So you could make a first guess by the file extension, for the SampleRateHertz you could use a tool like Tika by Apache. This outputs for the commercial_stereo.wav the following:
Content-Length: 6305632
Content-Type: audio/vnd.wave
X-Parsed-By: org.apache.tika.parser.DefaultParser
X-Parsed-By: org.apache.tika.parser.audio.AudioParser
X-TIKA:digest:MD5: 7e3e8837273e8bb143533894926f7da3
X-TIKA:digest:SHA256: 98fac004fb662ad8f720e680c81e3b4c9dea20190f5d1d908cece2cd6b30f01e
bits: 16
channels: 2
encoding: PCM_SIGNED
resourceName: commercial_stereo.wav
samplerate: 44100.0
xmpDM:audioSampleRate: 44100
xmpDM:audioSampleType: 16Int

Related

"audio/mpeg" stream api fails for some files plays some files?

We are recording some audios on Android phones which are having the following format as per vlc information:
Codec: MPEG AAC Audio (mp4a)
Language: English
Type: Audio
Channels: Stereo
Sample rate: 32000 Hz
Bits per sample: 32
The above files were not playing on the safari browser with mime type audio/mpeg, But as soon as we changed the mime to audio/mp4 it started playing on safari browser.
For Android we are using API to stream this file using api resource as follows :
#GET
#UnitOfWork
#Produces("audio/mpeg")
#Path("/getaudiofile/{fileId}")
public Response getPart(#Auth AuthUser authUser, #PathParam("fileId") Long fileId) {
File audioFile = new File(filesTableDAO.getFilePathById(fileId));
if(audioFile.exists()) {
return Response.ok().entity(audioFile).build();
} else {
// ... Return 404 here
}
}
But with above API some files getting played & some are not, Similar to Safari case earlier. But safari problem went away ASAP we changed mime to "audio/mp4" or "video/mp4" both the mime type work.
But for the API /getaudiofile/{fileId} none of the following mime types worked with the javax.ws.rs #Produces annotaion :
audio/mp4
video/mp4
audio/mpeg
audio/m4a
audio/mpeg-4
audio/mp4a
But with audio/mpeg some of the files play but some don't.
What may be the right mime type or can file set the codec or mime info itself while returning from API ?
Or Is there any way to make Android Media Player MIME type aware? Like html tag.
We have streamed file content of mime "audio/mpeg" the media player plays smaller sized files easily. But bigger streamed content fails to play e.g. 10 - 20 MB.
Problem with stream URL the player do not get any mime extension e.g. mp3, or mp4. Hence we want the media player to know in advance what type of the content is being streamed.
Does the MediaPlayer API support setting mime type to player instance prior to playing?
Update
1] This is happening for files with big sizes small files play very well, An recording of few seconds ( 1-50 secs ) play without a problem, An recording file with playback length of more than minute fails to play.
2] When played from authenticated URL playback fails if the same file is on local file system plays flawlessly.
If I understand your question correctly, perhaps you might try
openTypedAssetFile
public AssetFileDescriptor openTypedAssetFile (Uri uri,
String mimeTypeFilter,
Bundle opts)
Called by a client to open a read-only stream containing data of a particular MIME type. This is like
openAssetFile(Uri, String), except the file can only be read-only and
the content provider may perform data conversions to generate data of
the desired type.
Documentation for openTypedAssetFile is here.
Also look at the API for openWTypedAssetFileDescriptor here.
https://github.com/aruld/jersey-streaming
Above project by Arul Dhesiaseelan solved my issue, The way I wrote get file Resource was not efficient, In above GitHub project take look into MediaResource.java.
This is the proper way of streaming media files, Adjust mime-types as per your file.
I set headers to media player as follows:
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic <BASE64_ENCODED_AUTH_TOKEN>");
headers.put("Accept-Ranges", "bytes");
headers.put("Status", "206");
headers.put("Cache-control", "no-cache");
Uri uri = Uri.parse(url);
mediaPlayer.setDataSource(getContext(), uri, headers);
Now I am able to stream media with authentication.

Specific wav file failing to load while others load without errors

I'm working on a system to play, pause and stop music. I'm testing this out with 2 different wav files, one with a length of 45 seconds and other with a length of 3:35 minutes. The problem I'm having is that the 45 second wav file plays without any problem. The 3:35 minute wav file on the other hand, doesn't load. Is there a maximum time limit to wav files in java or is it possible the wav file is broken? It plays without any problem on windows app "groove music".
I've searched around on stack overflow but no one seemed to experience the same problem as I am, one wav file playing, the other one not.
Error code I'm getting:
javax.sound.sampled.LineUnavailableException: line with format PCM_FLOAT 44100.0 Hz, 32 bit, stereo, 8 bytes/frame, not supported.
The method i use for playing the wav file.
public static void playAudio(String name) {
try {
System.out.println("NOTE: Playing audio");
clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Engine.class.getResourceAsStream("/Audio/" + name));
clip.open(inputStream);
clip.start();
} catch(Exception e) {
System.out.println("ERROR: Failed to load audio");
}
}
Calling the method
Engine.playAudio("easy2.wav");
Picture of the wav files in the "src/Audio/" folder
Given the error message, one thing you could try is after opening the AudioInputStream from the resource, do the following:
AudioFormat fmt = inputStream.getFormat();
fmt = new AudioFormat(fmt.getSampleRate(),
16,
fmt.getChannels(),
true,
true);
inputStream = AudioSystem.getAudioInputStream(fmt, inputStream);
This attempts to convert the stream away from a floating-point format, hopefully to something that the system is more likely to support. (Also see JavaDoc for AudioSystem.getAudioInputStream(AudioFormat, AudioInputStream).)
You can run the following code to find out what formats are likely available for playback:
Arrays.stream(AudioSystem.getSourceLineInfo(new Line.Info(SourceDataLine.class)))
.filter(info -> info instanceof DataLine.Info)
.map(info -> (DataLine.Info) info)
.flatMap(info -> Arrays.stream(info.getFormats()))
.forEach(System.out::println);
If the above method of converting the audio stream doesn't work, then probably your best bet is to just convert the file with some editor, such as Audacity. Java sound is unfortunately still pretty limited in what formats it supports by default. (The most reliable format is probably CDDA, which is 44100Hz, 16-bit signed LPCM.)
There may also be 3rd-party SPIs which support conversions from floating-point PCM.
The problem I was facing originated in the wav file itself. Since a wav file can have one of several different formats, the one it was encoded with was not compatible with java. The solution was to change the bitrate and Hz of the wav file to match an encoding that java supported.
More about wav formats: https://en.wikipedia.org/wiki/WAV

JAVA using google speech recognition API

I'm trying to use google speech recognition API. Here's the code i've written:
http://pastebin.com/zJEhnJ74
It works. I get an answer from the server:
{"status":5,"id":"8803471b14a2310dfcf917754e8bd4a7-1","hypotheses":[]}
Now the problem is "status:5". Infact, here's status code:
status: 0 – correct
, status: 4 – missing audio file, 
status: 5 – incorrect audio file.
My problem is "incorrect audio file". I don't understand if it is a .flac file error (you can download my test .flac file here: http://www21.zippyshare.com/v/61888405/file.html) or how i read the file (in a byte array then convert it into string)
Thanks for help! and sorry for my bad english
You must use wr.write(data); instead of wr.writeBytes(new String(data));
Google answer:
{"status":0,"id":"e0f4ced346ad18bbb81756ed4d639164-1","hypotheses":[{"utterance":"hello how are you","confidence":0.94028234},{"utterance":"hello how r you"},{"utterance":"hello how are u"},{"utterance":"hello how are you in"}]}

How to read an ico format picture in java?

I have a lot of .ico formatted pictures, and I want to use them in my Java SE project, but it doesn't know the format. How can I work around this?
Try out image4j - Image Library for Java
The image4j library allows you to read and write certain image formats
in 100% pure Java.
Currently the following formats are supported:
BMP (Microsoft bitmap format - uncompressed; 1, 4, 8, 24 and 32 bit)
ICO (Microsoft icon format - 1, 4, 8, 24 and 32 bit [XP uncompressed,
Vista compressed])
With the library you can easily decode your ico file
List<BufferedImage> image = ICODecoder.read(new File("input.ico"));
Apache Commons Imaging allows to read and write ICO files:
List<BufferedImage> images = Imaging.getAllBufferedImages(new File("input.ico"));
It supports several popular formats of metadata too (EXIF, IPTC and XMP).
TwelveMonkeys ImageIO allows to extend the ImageIO API to support ICO and numerous other image file formats.
Hint for reading ico files with Apache Commons Imaging 1.0-alpha2:
There seems to be a difference in between reading ico files as a file and reading ico files as a byte[]: Imaging.getAllBufferedImages(File) reads an ico file, Imaging.getAllBufferedImages(new ByteArrayInputStream(byte[] icoFileContent, yourIcoFilename) also reads the ico file. Imaging.getAllBufferedImages(byte[]) does not read the same ico file but throws an ImageReadException. See code below.
File icoFile = new File("bluedot.ico");
// Works fine
List<BufferedImage> images = Imaging.getAllBufferedImages(icoFile);
Assert.assertFalse(images.isEmpty());
ImageIO.write(images.get(0), "png", new File("bluedot.png"));
// Also works fine
byte[] icoFileContent = Files.readAllBytes(icoFile.toPath());
images = Imaging.getAllBufferedImages(new ByteArrayInputStream(icoFileContent), "bluedot.ico");
Assert.assertFalse(images.isEmpty());
ImageIO.write(images.get(0), "png", new File("bluedot2.png"));
// Throws an exception
images = Imaging.getAllBufferedImages(icoFileContent);
Additionally here is a guide how I created the .ico file that is not readable by Apache Commons Imaging 1.0-alpha2 as byte[] (but is readable as File and is readable as ByteArrayInputStream):
Start GIMP (in my case version 2.10.22)
Window menu "File" > "New..."
Template: [empty]
Width: 48px
Height: 48px
Leave the rest as is (see screenshot below)
Draw something (e.g. a blue dot)
Window menu "File" > "Export as..."
File name: "bluedot.ico"
Icon Details: "4 bpp, 1-bit alpha, 16-slot palette"
Compressed (PNG): Not checked
Click "Export"
Imaging.getAllBufferedImages(byte[]) will throw org.apache.commons.imaging.ImageReadException: Can't parse this format.
Imaging.getAllBufferedImages(File) will read this file.

extracting tags of a song

How can I extract tags(album, artist, album art, etc) from an mp3 file using java? I need all the tags of my songs to be stored at one particular file so that I can use it as a database.
you can use Tika:
http://tika.apache.org/
this metadata extracted by Tika for MP3 file:
Author: /ÅÍÓÜÜÇÓ ..
Content-Length: 4232049
Content-Type: audio/mpeg
channels: 2
resourceName: droob_al-hayat.MP3
samplerate: 44100
title:
version: MPEG 3 Layer III Version 1
xmpDM:album:
xmpDM:artist: /ÅÍÓÜÜÇÓ ..
xmpDM:audioChannelType: Stereo
xmpDM:audioCompressor: MP3
xmpDM:audioSampleRate: 44100
xmpDM:composer: null
xmpDM:genre:
xmpDM:logComment:
xmpDM:releaseDate:

Categories

Resources