Search Results

Search found 37 results on 2 pages for 'audioformat'.

Page 1/2 | 1 2  | Next Page >

  • How to play audio in Java Application

    - by user577829
    I'm making a java application and I need to play audio. I'm playing mainly small sound files of my cannon firing (its a cannon shooting game) and the projectiles exploding, though I plan on having looping background music. I have found two different methods to accomplish this, but both don't work how I want. The first method is literally a method: public void playSoundFile(File file) {//http://java.ittoolbox.com/groups/technical-functional/java-l/sound-in-an-application-90681 try { //get an AudioInputStream AudioInputStream ais = AudioSystem.getAudioInputStream(file); //get the AudioFormat for the AudioInputStream AudioFormat audioformat = ais.getFormat(); System.out.println("Format: " + audioformat.toString()); System.out.println("Encoding: " + audioformat.getEncoding()); System.out.println("SampleRate:" + audioformat.getSampleRate()); System.out.println("SampleSizeInBits: " + audioformat.getSampleSizeInBits()); System.out.println("Channels: " + audioformat.getChannels()); System.out.println("FrameSize: " + audioformat.getFrameSize()); System.out.println("FrameRate: " + audioformat.getFrameRate()); System.out.println("BigEndian: " + audioformat.isBigEndian()); //ULAW format to PCM format conversion if ((audioformat.getEncoding() == AudioFormat.Encoding.ULAW) || (audioformat.getEncoding() == AudioFormat.Encoding.ALAW)) { AudioFormat newformat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioformat.getSampleRate(), audioformat.getSampleSizeInBits() * 2, audioformat.getChannels(), audioformat.getFrameSize() * 2, audioformat.getFrameRate(), true); ais = AudioSystem.getAudioInputStream(newformat, ais); audioformat = newformat; } //checking for a supported output line DataLine.Info datalineinfo = new DataLine.Info(SourceDataLine.class, audioformat); if (!AudioSystem.isLineSupported(datalineinfo)) { //System.out.println("Line matching " + datalineinfo + " is not supported."); } else { //System.out.println("Line matching " + datalineinfo + " is supported."); //opening the sound output line SourceDataLine sourcedataline = (SourceDataLine) AudioSystem.getLine(datalineinfo); sourcedataline.open(audioformat); sourcedataline.start(); //Copy data from the input stream to the output data line int framesizeinbytes = audioformat.getFrameSize(); int bufferlengthinframes = sourcedataline.getBufferSize() / 8; int bufferlengthinbytes = bufferlengthinframes * framesizeinbytes; byte[] sounddata = new byte[bufferlengthinbytes]; int numberofbytesread = 0; while ((numberofbytesread = ais.read(sounddata)) != -1) { int numberofbytesremaining = numberofbytesread; sourcedataline.write(sounddata, 0, numberofbytesread); } } } catch (Exception e) { e.printStackTrace(); } } The problem with this is that my entire program stops until the sound file is finished, or at least nearly finished. The second method is this: File file = new File("Launch1.wav"); AudioClip clip; try { clip = JApplet.newAudioClip(file.toURL()); clip.play(); } catch (Exception e) { e.getMessage(); } The problem I have here is that every time the sound file ends early or doesn't play at all depending on where I place the code. Is their any way to play sound without the above mentioned problems? Am I doing something wrong? Any help is greatly appreciated.

    Read the article

  • Play wave file using AudioFormat in java

    - by angelina
    Dear all, I m getting following exception while running my code on linux operating system.This code works fine on windows operating system.below is the exception and code used. java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian is supported. AudioFormat format = sourceaudio.getFormat(); format = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); AudioFileFormat.Type targettype = AudioFileFormat.Type.WAVE; AudioInputStream targetaudiostream = AudioSystem.getAudioInputStream(format, sourceaudio); sourceaudio.close(); targetaudiostream.close(); System.out.println("55555555"); URL url = new URL("http://localhost:8084/newvideo/PCMfile.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(url); clip.open(ais); System.out.println("seconds: " + (clip.getMicrosecondLength() / 1000000));

    Read the article

  • SOS: AudioFormat when writing to file in FreeTTS

    - by user330793
    Very annoying problem. I have developed a freeTTS application of the freetts class that write captured audio to file however I am having some very annoying problems. When setting the audio player to singlefileaudio player I try to also set the audioformat with my own default values for sampleRate, sampleSizeInBits, channels, signed and bigEndian. Now I access AudioPlayer.get methods to show these values in runtime just to ensure they are set to what I set them and they match those values. However when file writing completes and I check the properties of the resulting wave file, they are set to the audioPlayer default settings. Normally this will be fine except I have to read the files into another application which has fixed audio property settings so I always get a resulting output that sounds like am fast forwarding the sound and listening to it at the same time. Obviously because of the different sampling rates. I need help please. Thanx, Henry

    Read the article

  • How to configure the framesize using AudioUnit.framework on iOS

    - by Piperoman
    I have an audio app i need to capture mic samples to encode into mp3 with ffmpeg First configure the audio: /** * We need to specifie our format on which we want to work. * We use Linear PCM cause its uncompressed and we work on raw data. * for more informations check. * * We want 16 bits, 2 bytes (short bytes) per packet/frames at 8khz */ AudioStreamBasicDescription audioFormat; audioFormat.mSampleRate = SAMPLE_RATE; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFormatFlags = kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger; audioFormat.mFramesPerPacket = 1; audioFormat.mChannelsPerFrame = 1; audioFormat.mBitsPerChannel = audioFormat.mChannelsPerFrame*sizeof(SInt16)*8; audioFormat.mBytesPerPacket = audioFormat.mChannelsPerFrame*sizeof(SInt16); audioFormat.mBytesPerFrame = audioFormat.mChannelsPerFrame*sizeof(SInt16); The recording callback is: static OSStatus recordingCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { NSLog(@"Log record: %lu", inBusNumber); NSLog(@"Log record: %lu", inNumberFrames); NSLog(@"Log record: %lu", (UInt32)inTimeStamp); // the data gets rendered here AudioBuffer buffer; // a variable where we check the status OSStatus status; /** This is the reference to the object who owns the callback. */ AudioProcessor *audioProcessor = (__bridge AudioProcessor*) inRefCon; /** on this point we define the number of channels, which is mono for the iphone. the number of frames is usally 512 or 1024. */ buffer.mDataByteSize = inNumberFrames * sizeof(SInt16); // sample size buffer.mNumberChannels = 1; // one channel buffer.mData = malloc( inNumberFrames * sizeof(SInt16) ); // buffer size // we put our buffer into a bufferlist array for rendering AudioBufferList bufferList; bufferList.mNumberBuffers = 1; bufferList.mBuffers[0] = buffer; // render input and check for error status = AudioUnitRender([audioProcessor audioUnit], ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList); [audioProcessor hasError:status:__FILE__:__LINE__]; // process the bufferlist in the audio processor [audioProcessor processBuffer:&bufferList]; // clean up the buffer free(bufferList.mBuffers[0].mData); //NSLog(@"RECORD"); return noErr; } With data: inBusNumber = 1 inNumberFrames = 1024 inTimeStamp = 80444304 // All the time same inTimeStamp, this is strange However, the framesize that i need to encode mp3 is 1152. How can i configure it? If i do buffering, that implies a delay, but i would like to avoid this because is a real time app. If i use this configuration, each buffer i get trash trailing samples, 1152 - 1024 = 128 bad samples. All samples are SInt16.

    Read the article

  • Difficulty porting raw PCM output code from Java to Android AudioTrack API.

    - by IndigoParadox
    I'm attempting to port an application that plays chiptunes (NSF, SPC, etc) music files from Java SE to Android. The Android API seems to lack the javax multimedia classes that this application uses to output raw PCM audio. The closest analog I've found in the API is AudioTrack and so I've been wrestling with that. However, when I try to run one of my sample music files through my port-in-progress, all I get back is static. My suspicion is that it's the AudioTrack I've setup which is at fault. I've tried various different constructors but it all just outputs static in the end. The DataLine setup in the original code is something like: AudioFormat audioFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, true ); DataLine.Info lineInfo = new DataLine.Info( SourceDataLine.class, audioFormat ); DataLine line = (SourceDataLine)AudioSystem.getLine( lineInfo ); The constructor I'm using right now is: AudioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, AudioTrack.getMinBufferSize( 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT ), AudioTrack.MODE_STREAM ); I've replaced constants and variables in those so they make sense as concisely as possible, but my basic question is if there are any obvious problems in the assumptions I made when going from one format to the other.

    Read the article

  • audio frameworks in iPhone

    - by suse
    Hello, I would like to know the follwing information about iPhone audio system Heirarchy of the audio framework in iPhone OS. i know that there are 3 main audio frameworks in iPhone OS.i.e AVFoundation Framework CoreAudio Framework OpenAL Framework what are the audio formats supported in each of the above framework?I mean will all the framework support all audio formats or are they dependent about the audio formats it support? Thank You

    Read the article

  • Android - Getting audio to play through earpiece

    - by Donal Rafferty
    I currently have code that reads a recording in from the devices mic using the AudioRecord class and then playing it back out using the AudioTrack class. My problem is that when I play it out it plays vis the speaker phone. I want it to play out via the ear piece on the device. Here is my code: public class LoopProg extends Activity { boolean isRecording; //currently not used AudioManager am; int count = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.setMicrophoneMute(true); while(count <= 1000000){ Record record = new Record(); record.run(); count ++; Log.d("COUNT", "Count is : " + count); } } public class Record extends Thread { static final int bufferSize = 200000; final short[] buffer = new short[bufferSize]; short[] readBuffer = new short[bufferSize]; public void run() { isRecording = true; android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize); AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM); am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC); int ok = am.getRouting(AudioManager.ROUTE_EARPIECE); Log.d("ROUTING", "getRouting = " + ok); setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); //am.setSpeakerphoneOn(true); Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn()); am.setSpeakerphoneOn(false); Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn()); atrack.setPlaybackRate(11025); byte[] buffer = new byte[buffersize]; arec.startRecording(); atrack.play(); while(isRecording) { arec.read(buffer, 0, buffersize); atrack.write(buffer, 0, buffer.length); } arec.stop(); atrack.stop(); isRecording = false; } } } As you can see if the code I have tried using the AudioManager class and its methods including the deprecated setRouting method and nothing works, the setSpeatPoneOn method seems to have no effect at all, neither does the routing method. Has anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone?

    Read the article

  • Streaming input to System.Speech.Recognition.SpeechRecognitionEngine

    - by spurserh
    I am trying to do "streaming" speech recognition in C# from a TCP socket. The problem I am having is that SpeechRecognitionEngine.SetInputToAudioStream() seems to require a Stream of a defined length which can seek. Right now the only way I can think to make this work is to repeatedly run the recognizer on a MemoryStream as more input comes in. Here's some code to illustrate: SpeechRecognitionEngine appRecognizer = new SpeechRecognitionEngine(); System.Speech.AudioFormat.SpeechAudioFormatInfo formatInfo = new System.Speech.AudioFormat.SpeechAudioFormatInfo(8000, System.Speech.AudioFormat.AudioBitsPerSample.Sixteen, System.Speech.AudioFormat.AudioChannel.Mono); NetworkStream stream = new NetworkStream(socket,true); appRecognizer.SetInputToAudioStream(stream, formatInfo); // At the line above a "NotSupportedException" complaining that "This stream does not support seek operations." Does anyone know how to get around this? It must support streaming input of some sort, since it works fine with the microphone using SetInputToDefaultAudioDevice(). Thanks, Sean

    Read the article

  • Problem using AudioRecord with 8-bit encoding in android

    - by maxsap
    Hello, I have made an application that records from the phones microphone using the AudioRecord and 16-bit encoding, and I am able to playback the recording. For some compatibility reason I need to use 8-bit encoding, but when I try to run the same program using that encoding I keep getting an Invalid Audio Format. my code is : int bufferSize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT); AudioRecord recordInstance = new AudioRecord( MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, bufferSize); Any one knows what is the problem? according to the documentation AudioRecord is capable of 8-bit encoding. thanks in advanced maxsap.

    Read the article

  • Android:Playing bigger size audio wav sound file produces crash

    - by user187532
    Hi Android experts, I am trying to play the bigger size audio wav file(which is 20 mb) using the following code(AudioTrack) on my Android 1.6 HTC device which basically has less memory. But i found device crash as soon as it executes reading, writing and play. But the same code works fine and plays the lesser size audio wav files(10kb, 20 kb files etc) very well. P.S: I should play PCM(.wav) buffer sound, the reason behind why i use AudioTrack here. Though my device has lesser memory, how would i read bigger audio files bytes by bytes and play the sound to avoid crashing due to memory constraints. private void AudioTrackPlayPCM() throws IOException { String filePath = "/sdcard/myWav.wav"; // 8 kb file byte[] byteData = null; File file = null; file = new File(filePath); byteData = new byte[(int) file.length()]; FileInputStream in = null; try { in = new FileInputStream( file ); in.read( byteData ); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT); AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, intSize, AudioTrack.MODE_STREAM); at.play(); at.write(byteData, 0, byteData.length); at.stop(); at.release(); } Could someone guide me please to play the AudioTrack code for bigger size wav files?

    Read the article

  • how to continuously send data without blocking?

    - by Donal Rafferty
    I am trying to send rtp audio data from my Android application. I currently can send 1 RTP packet with the code below and I also have another class that extends Thread that listens to and receives RTP packets. My question is how do I continuously send my updated buffer through the packet payload without blocking the receiving thread? public void run() { isRecording = true; android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); int buffersize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); Log.d("BUFFERSIZE","Buffer size = " + buffersize); arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize); short[] readBuffer = new short[80]; byte[] buffer = new byte[160]; arec.startRecording(); while(arec.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING){ int frames = arec.read(readBuffer, 0, 80); @SuppressWarnings("unused") int lenghtInBytes = codec.encode(readBuffer, 0, buffer, frames); RtpPacket rtpPacket = new RtpPacket(); rtpPacket.setV(2); rtpPacket.setX(0); rtpPacket.setM(0); rtpPacket.setPT(0); rtpPacket.setSSRC(123342345); rtpPacket.setPayload(buffer, 160); try { rtpSession2.sendRtpPacket(rtpPacket); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RtpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } So when I send on one device and receive on another I get decent audio, but when I send and receive on both I get broken sound like its taking turns to send and receive audio. I have a feeling it could be to do with the while loop? it could be looping around in there and not letting anything else run?

    Read the article

  • Android: Streaming audio over TCP Sockets

    - by user299988
    Hi, For my app, I need to record audio from MIC on an Android phone, and send it over TCP to the other android phone, where it needs to be played. I am using AudioRecord and AudioTrack class. This works great with a file - write audio to the file using DataOutputStream, and read from it using DataInputStream. However, if I obtain the same stream from a socket instead of a File, and try writing to it, I get an exception. I am at a loss to understand what could possibly be going wrong. Any help would be greatly appreciated. EDIT: The problem is same even if I try with larger buffer sizes (65535 bytes, 160000 bytes). This is the code: Recorder: int bufferSize = AudioRecord.getMinBufferSize(11025, , AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioRecord recordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize); byte[] tempBuffer = new byte[bufferSize]; recordInstance.startRecording(); while (/*isRecording*/) { bufferRead = recordInstance.read(tempBuffer, 0, bufferSize); dataOutputStreamInstance.write(tempBuffer); } The DataOutputStream above is obtained as: BufferedOutputStream buff = new BufferedOutputStream(out1); //out1 is the socket's outputStream DataOutputStream dataOutputStreamInstance = new DataOutputStream (buff); Could you please have a look, and let me know what is it that I could be doing wrong here? Thanks,

    Read the article

  • AudioRecord - empty buffer

    - by Arxas
    I' m trying to record some audio using AudioRecord class. Here is my code: int audioSource = AudioSource.MIC; int sampleRateInHz = 44100; int channelConfig = AudioFormat.CHANNEL_IN_MONO; int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int bufferSizeInShorts = 44100; int bufferSizeInBytes = 2*bufferSizeInShorts; short Data[] = new short[bufferSizeInShorts]; Thread recordingThread; AudioRecord audioRecorder = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void startRecording(View arg0) { audioRecorder.startRecording(); recordingThread = new Thread(new Runnable() { public void run() { while (Data[bufferSizeInShorts-1] == 0) audioRecorder.read(Data, 0, bufferSizeInShorts); } }); audioRecorder.stop(); } Unfortunately my short array is empty after the recording is over. May I kindly ask you to help me figure out what's wrong?

    Read the article

  • Voice echo in UDP based voice transmission [closed]

    - by Meherzad
    I have coded a java application for voice transmission between to ip in LAN. Here the code. public static Boolean flag= true; public static Boolean recFlag=true; DatagramSocket UDPSocket=null; AudioFormat format = null; TargetDataLine microphone=null; byte[] buffer=null; DatagramPacket UDPPacket=null; public void startChat(String ipAddress){ try{ buffer = new byte[1000]; UDPSocket=new DatagramSocket(1987); Thread th=new Thread(new Listener()); th.start(); microphone = AudioSystem.getTargetDataLine(format); format= new AudioFormat(8000.0f, 16, 1, true, true); UDPPacket = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(ipAddress), 1988); microphone.open(format); microphone.start(); while (flag) { microphone.read(buffer, 0, buffer.length); UDPSocket.send(UDPPacket); } } catch(Exception e){ System.out.println(" ssss "+e.getMessage()); } } public class Listener extends Thread{ byte[] buff=new byte[1000]; DatagramSocket UDPSocket1=null; DatagramPacket recPacket=null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine line=null; @Override public void run(){ try{ UDPSocket1=new DatagramSocket(1988); format= new AudioFormat(8000.0f, 16, 1, true, true); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); } catch(Exception e){ System.out.println("list "+ e.getMessage()); } recPacket=new DatagramPacket(buff, buff.length); while(recFlag){ try{ UDPSocket1.receive(recPacket); buff = (byte[])recPacket.getData(); line.write(buff, 0, buff.length); } catch(Exception e){ System.out.println("errr "+e.getMessage()); } } line.drain(); line.close(); } } Main problem which I am facing that I am getting only echo of my own voice. I am unable to hear voice from the other end only I am hearing is my own voice. Please suggest any solution.

    Read the article

  • Switch between speakerphone and headset on Android

    - by user210504
    Hi! I wish to know if there is a way, using which we can switch between the speaker and headset dynamically in an android application. I am using this sample code, I found online for my experiments final float frequency = 440; float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample float angle = 0; AndroidAudioDevice device = new AndroidAudioDevice( ); AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE); am.setMode(AudioManager.MODE_IN_CALL); float samples[] = new float[1024]; int count = 0; while( count < 10 ) { count++; for( int i = 0; i < samples.length; i++ ) { samples[i] = (float)Math.sin( angle ) ; angle += increment; } device.writeSamples( samples ); } device.stop(); am.setMode(AudioManager.MODE_NORMAL); ---- next class public class AndroidAudioDevice { AudioTrack track; short[] buffer = new short[1024]; public AndroidAudioDevice( ) { int minSize =AudioTrack.getMinBufferSize( 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT ); track = new AudioTrack( AudioManager.STREAM_VOICE_CALL, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM); track.play(); } public void writeSamples(float[] samples) { fillBuffer( samples ); track.write( buffer, 0, samples.length ); } private void fillBuffer( float[] samples ) { if( buffer.length < samples.length ) buffer = new short[samples.length]; for( int i = 0; i < samples.length; i++ ) buffer[i] = (short)(samples[i] * Short.MAX_VALUE);; } public void stop() { track.stop(); } } As per my understanding this should play audio on headset, because we have not enabled the speaker phone. However, the audio is playing on the speaker phone. 1 Am I doing something wrong here? 2 What would be a way to switch between internal speaker and speaker phone dynamically for same code peice Any help will be appreciated.

    Read the article

  • Avoiding shutdown hook

    - by meryl
    Through the following code I can play and cut and audio file. Is there any other way to avoid using a shutdown hook? The problem is that whenever I push the cut button , the file doesn't get saved until I close the application thanks ...................... void play_cut() { try { // First, we get the format of the input file final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType(); // Then, we get a clip for playing the audio. c = AudioSystem.getClip(); // We get a stream for playing the input file. AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio); // We use the clip to open (but not start) the input stream c.open(ais); // We get the format of the audio codec (not the file format we got above) final AudioFormat audioFormat = ais.getFormat(); // We add a shutdown hook, an anonymous inner class. Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { // We're now in the hook, which means the program is shutting down. // You would need to use better exception handling in a production application. try { // Stop the audio clip. c.stop(); // Create a new input stream, with the duration set to the frame count we reached. Note that we use the previously determined audio format AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition()); // Write it out to the output file, using the same file type. AudioSystem.write(startStream, fileType, outputAudio); } catch(IOException e) { e.printStackTrace(); } } }); // After setting up the hook, we start the clip. c.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } }// end play_cut ......................

    Read the article

  • Help file not working

    - by meryl
    Hi, can anyone help me ? I wanto to play an audio file and whenever I press the stop button , the already played part of the file should be saved. Unfortunately , what I get is an audio file (.wav) which actually is unplayable. Thanks //**************************** void play_cut() { try { // First, we get the format of the input file final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType(); // Then, we get a clip for playing the audio. c = AudioSystem.getClip(); // We get a stream for playing the input file. AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio); // We use the clip to open (but not start) the input stream c.open(ais); // We get the format of the audio codec (not the file format we got above) final AudioFormat audioFormat = ais.getFormat(); c.start(); AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition()); AudioSystem.write(startStream, fileType, outputAudio); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } }// end play_cut //****************************

    Read the article

  • How to send audio stream via UDP in java?

    - by Nob Venoda
    Hi to all :) I have a problem, i have set MediaLocator to microphone input, and then created Player. I need to grab that sound from the microphone, encode it to some lower quality stream, and send it as a datagram packet via UDP. Here's the code, i found most of it online and adapted it to my app: public class AudioSender extends Thread { private MediaLocator ml = new MediaLocator("javasound://44100"); private DatagramSocket socket; private boolean transmitting; private Player player; TargetDataLine mic; byte[] buffer; private AudioFormat format; private DatagramSocket datagramSocket(){ try { return new DatagramSocket(); } catch (SocketException ex) { return null; } } private void startMic() { try { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0F, 16, 2, 4, 8000.0F, true); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); mic = (TargetDataLine) AudioSystem.getLine(info); mic.open(format); mic.start(); buffer = new byte[1024]; } catch (LineUnavailableException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } private Player createPlayer() { try { return Manager.createRealizedPlayer(ml); } catch (IOException ex) { return null; } catch (NoPlayerException ex) { return null; } catch (CannotRealizeException ex) { return null; } } private void send() { try { mic.read(buffer, 0, 1024); DatagramPacket packet = new DatagramPacket( buffer, buffer.length, InetAddress.getByName(Util.getRemoteIP()), 91); socket.send(packet); } catch (IOException ex) { Logger.getLogger(AudioSender.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void run() { player = createPlayer(); player.start(); socket = datagramSocket(); transmitting = true; startMic(); while (transmitting) { send(); } } public static void main(String[] args) { AudioSender as = new AudioSender(); as.start(); } } And only thing that happens when I run the receiver class, is me hearing this Player from the sender class. And I cant seem to see the connection between TargetDataLine and Player. Basically, I need to get the sound form player, and somehow convert it to bytes[], therefore I can sent it as datagram. Any ideas? Everything is acceptable, as long as it works :)

    Read the article

  • How do I get a mp3 file's total time in Java?

    - by Tom Brito
    The answers provided in How do I get a sound file’s total time in Java? work well for wav files, but not for mp3 files. They are (given a file): AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file); AudioFormat format = audioInputStream.getFormat(); long frames = audioInputStream.getFrameLength(); double durationInSeconds = (frames+0.0) / format.getFrameRate(); and: AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file); AudioFormat format = audioInputStream.getFormat(); long audioFileLength = file.length(); int frameSize = format.getFrameSize(); float frameRate = format.getFrameRate(); float durationInSeconds = (audioFileLength / (frameSize * frameRate)); They give the same correct result for wav files, but wrong and different results for mp3 files. Any idea what do I have to do to get the mp3 file's duration?

    Read the article

  • Question SpeechSynthesizer.SetOutputToAudioStream audio format problem

    - by Chris Kugler
    Hi, I'm currently working on an application which requires transmission of speech encoded to a specific audio format. System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat = new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm, 8000, 16, 1, 16000, 2, null); This states that the audio is in PCM format, 8000 samples per second, 16 bits per sample, mono, 16000 average bytes per second, block alignment of 2. When I attempt to execute the following code there is nothing written to my MemoryStream instance; however when I change from 8000 samples per second up to 11025 the audio data is written successfully. SpeechSynthesizer synthesizer = new SpeechSynthesizer(); waveStream = new MemoryStream(); PromptBuilder pbuilder = new PromptBuilder(); PromptStyle pStyle = new PromptStyle(); pStyle.Emphasis = PromptEmphasis.None; pStyle.Rate = PromptRate.Fast; pStyle.Volume = PromptVolume.ExtraLoud; pbuilder.StartStyle(pStyle); pbuilder.StartParagraph(); pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Teen, 2); pbuilder.StartSentence(); pbuilder.AppendText("This is some text."); pbuilder.EndSentence(); pbuilder.EndVoice(); pbuilder.EndParagraph(); pbuilder.EndStyle(); synthesizer.SetOutputToAudioStream(waveStream, synthFormat); synthesizer.Speak(pbuilder); synthesizer.SetOutputToNull(); There are no exceptions or errors recorded when using a sample rate of 8000 and I couldn't find anything useful in the documentation regarding SetOutputToAudioStream and why it succeeds at 11025 samples per second and not 8000. I have a workaround involving a wav file that I generated and converted to the correct sample rate using some sound editing tools, but I would like to generate the audio from within the application if I can. One particular point of interest was that the SpeechRecognitionEngine accepts that audio format and successfully recognized the speech in my synthesized wave file... Update: Recently discovered that this audio format succeeds for certain installed voices, but fails for others. It fails specifically for LH Michael and LH Michelle, and failure varies for certain voice settings defined in the PromptBuilder.

    Read the article

  • AudioRecord doesn't work for Motorola Milestone

    - by hcpl
    I'm having this problem only on Motorola Milestone. Code: // init recorder recordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, 8000); recordInstance.startRecording(); //more code here recordInstance.stop(); The errorinformation I have (can't find more for the moment since I don't have a milestone myself for debugging): Uncaught handler: thread main exiting due to uncaught exception java.lang.IllegalStateException: stop() called on an uninitialized AudioRecord. at android.media.AudioRecord.stop(AudioRecord.java:51 6) Apparantly I'm not the only one with this problem. Some very similar threads I found (without solution): http://groups.google.com/group/android-developers/browse_thread/thread/6dd24aeb484b2e40 http://androidcommunity.com/forums/f2/problem-using-audiorecord-in-motorola-milestone-30935/ http://community.developer.motorola.com/t5/Android-App-Development-for/Problem-using-AudioRecord-on-Milestone-device/m-p/3889 http://www.fring.com/forums/showthread.php?t=16194

    Read the article

  • How do I handle calls to AudioTrack from jni without crashing?

    - by icecream
    I was trying to write to an AudioTrack from a jni callback, and I get a signal 7 (SIGBUS), fault addr 00000000. I have looked at the Wolf3D example for odroid and they seem to use a android.os.Handler to post a Runnable that will do an update in the correct thread context. I have also tried AttachCurrentThread, but I fail in this case also. It works to play the sound when running from the constructor even if I wrap it in a thread and then post it to the handler. When I do the "same" via a callback from jni it fails. I assume I am braeaking some rules, but I haven't been able to figure out what they are. So far, I haven't found the answer here on SO. So I wonder if anyone knows how this should be done. EDIT: Answered below. The following code is to illustrate the problem. Java: package com.example.jniaudiotrack; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class JniAudioTrackActivity extends Activity { AudioTrack mAudioTrack; byte[] mArr; public static final Handler mHandler = new Handler(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mArr = new byte[2048]; for (int i = 0; i < 2048; i++) { mArr[i] = (byte) (Math.sin(i) * 128); } mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, 2048, AudioTrack.MODE_STREAM); mAudioTrack.play(); new Thread(new Runnable() { public void run() { mHandler.post(new Runnable() { public void run() { mAudioTrack.write(mArr, 0, 2048); Log.i(TAG, "*** Handler from constructor ***"); } }); } }).start(); new Thread(new Runnable() { public void run() { audioFunc(); } }).start(); } public native void audioFunc(); @SuppressWarnings("unused") private void audioCB() { mHandler.post(new Runnable() { public void run() { mAudioTrack.write(mArr, 0, 2048); Log.i(TAG, "*** audioCB called ***"); } }); } private static final String TAG = "JniAudioTrackActivity"; static { System.loadLibrary("jni_audiotrack"); } } cpp: #include <jni.h> extern "C" { JNIEXPORT void Java_com_example_jniaudiotrack_JniAudioTrackActivity_audioFunc(JNIEnv* env, jobject obj); } JNIEXPORT void Java_com_example_jniaudiotrack_JniAudioTrackActivity_audioFunc(JNIEnv* env, jobject obj) { JNIEnv* jniEnv; JavaVM* vm; env->GetJavaVM(&vm); vm->AttachCurrentThread(&jniEnv, 0); jclass cls = env->GetObjectClass(obj); jmethodID audioCBID = env->GetMethodID(cls, "audioCB", "()V"); if (!audioCBID) { return; } env->CallVoidMethod(cls, audioCBID); } Trace snippet: I/DEBUG ( 1653): pid: 9811, tid: 9811 >>> com.example.jniaudiotrack <<< I/DEBUG ( 1653): signal 7 (SIGBUS), fault addr 00000000 I/DEBUG ( 1653): r0 00000800 r1 00000026 r2 00000001 r3 00000000 I/DEBUG ( 1653): r4 42385726 r5 41049e54 r6 bee25570 r7 ad00e540 I/DEBUG ( 1653): r8 000040f8 r9 41048200 10 41049e44 fp 00000000 I/DEBUG ( 1653): ip 000000f8 sp bee25530 lr ad02dbb5 pc ad012358 cpsr 20000010 I/DEBUG ( 1653): #00 pc 00012358 /system/lib/libdvm.so

    Read the article

  • AudioRecord problems with non-HTC devices

    - by Marc
    I'm having troubles using AudioRecord. An example using some of the code derived from the splmeter project: private static final int FREQUENCY = 8000; private static final int CHANNEL = AudioFormat.CHANNEL_CONFIGURATION_MONO; private static final int ENCODING = AudioFormat.ENCODING_PCM_16BIT; private int BUFFSIZE = 50; private AudioRecord recordInstance = null; ... android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); recordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC, FREQUENCY, CHANNEL, ENCODING, 8000); recordInstance.startRecording(); short[] tempBuffer = new short[BUFFSIZE]; int retval = 0; while (this.isRunning) { for (int i = 0; i < BUFFSIZE - 1; i++) { tempBuffer[i] = 0; } retval = recordInstance.read(tempBuffer, 0, BUFFSIZE); ... // process the data } This works on the HTC Dream and the HTC Magic perfectly without any log warnings/errors, but causes problems on the emulators and Nexus One device. On the Nexus one, it simply never returns useful data. I cannot provide any other useful information as I'm having a remote friend do the testing. On the emulators (Android 1.5, 2.1 and 2.2), I get weird errors from the AudioFlinger and Buffer overflows with the AudioRecordThread. I also get a major slowdown in UI responsiveness (even though the recording takes place in a separate thread than the UI). Is there something apparent that I'm doing incorrectly? Do I have to do anything special for the Nexus One hardware?

    Read the article

1 2  | Next Page >