Pausing Audio Recording in Java2019 Community Moderator ElectionHow to pause audio recording in javaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java

How do spaceships determine each other's mass in space?

What was so special about The Piano that Ada was willing to do anything to have it?

Giving a career talk in my old university, how prominently should I tell students my salary?

-1 to the power of a irrational number

Too soon for a plot twist?

Is it a Cyclops number? "Nobody" knows!

How to educate team mate to take screenshots for bugs with out unwanted stuff

What is the purpose of a disclaimer like "this is not legal advice"?

What is Tony Stark injecting into himself in Iron Man 3?

Why does Central Limit Theorem break down in my simulation?

Is there a way to make cleveref distinguish two environments with the same counter?

How to install round brake pads

Why restrict private health insurance?

Smooth vector fields on a surface modulo diffeomorphisms

Are small insurances worth it?

What will happen if my luggage gets delayed?

Can I negotiate a patent idea for a raise, under French law?

Why do phishing e-mails use faked e-mail addresses instead of the real one?

When an outsider describes family relationships, which point of view are they using?

Yet another question on sums of the reciprocals of the primes

I am the person who abides by rules, but breaks the rules. Who am I?

How to open new window on center of screen

Is it possible to clone a polymorphic object without manually adding overridden clone method into each derived class in C++?

Do Paladin Auras of Differing Oaths Stack?



Pausing Audio Recording in Java



2019 Community Moderator ElectionHow to pause audio recording in javaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java










3















I am trying to implement a pause/resume functionality for my audio recording module in Java. So far all I have found on SO is this, which does not give a definitive answer - I have tried the answerer's suggestion of calling start() and stop() on the TargetDataLine to achieve this, and am aware that stop() (from Oracle):



"Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible."



However I am finding that when I call stop on my TargetDataLine, then sleep for five seconds and call start() to reopen it, the recording never resumes. Here is the code:



import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.*;
import javax.sound.sampled.AudioFileFormat.Type;

public class AudioRecorder

static TargetDataLine targetLine = null;
static final long maxRecordingTime = 3600000; // One hour in milliseconds
static Thread recordThread;

public static void main(String[] args)

try

// Initialise audio format settings and setup data line matching format specification

initialiseAudioSettings();

catch (LineUnavailableException e)

e.printStackTrace();


// TEST

startRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to pause recording...");

pauseRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to resume recording...");

resumeRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to stop recording...");

stopRecording();

System.out.println("Recording stopped...(in theory)");

// /TEST


private static void initialiseAudioSettings() throws LineUnavailableException

// Define audio format as:
// Encoding: Linear PCM
// Sample Rate: 44.1 kHz
// Bit Depth: 16-bit
// Channel Format: Stereo
// Data Storage: Signed & Big-Endian

final AudioFormat audioFormat = new AudioFormat(44100, 16, 2, true, true);

// Store format metadata in an Info variable

final DataLine.Info audioFormatInfo = new DataLine.Info(TargetDataLine.class, audioFormat);

if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE))

throw new LineUnavailableException("No microphone has been detected. Please reconnect the microphone and try again.");
else

System.out.println("Microphone detected. Querying target data line...");


// Use metadata to ascertain whether audio format is supported by default input device

if (AudioSystem.isLineSupported(audioFormatInfo) == false)

throw new LineUnavailableException("The default input device does not support the specified audio output format");


// Get a line matching the specified audio format

targetLine = (TargetDataLine)AudioSystem.getLine(audioFormatInfo);

// Instruct the system to allocate resources to the targetLine and switch it on

targetLine.open();

// Prepare line for audio input

targetLine.start();


private static void startRecording()

TimerTask scheduleRecordingEnd = new TimerTask()

public void run()

stopRecording();

;

Timer recordingTimer = new Timer("Recording Timer");

recordingTimer.schedule(scheduleRecordingEnd, maxRecordingTime);

// Setup recording thread

recordThread = new Thread(new Runnable()

@Override
public void run()


// Route audio input stream to target data line

AudioInputStream audioInputStream = new AudioInputStream(targetLine);

// Instantiate output filepath & filename

File outputFile = new File("C:/temp/test.wav");

// Write input audio to output .wav file

try

AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);

catch (IOException e)

e.printStackTrace();



);

// Start recording

recordThread.start();


private static void pauseRecording()

targetLine.stop();


private static void resumeRecording()

targetLine.start();


private static void stopRecording()

// Cease all I/O functions of the line

targetLine.stop();

// Close the line, deallocating system resources and deleting metadata

targetLine.close();

System.out.println("Stopping recording...");

recordThread.stop();




The parts of this code that should be of interest are the tests in main() and the startRecording(), pauseRecording() and resumeRecording() functions, although I have included the code in its entirety for completeness.



Could anyone point me in the right direction as to why this might be happening? Any help would be much appreciated.










share|improve this question






















  • I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

    – Mokarrom Hossain
    yesterday















3















I am trying to implement a pause/resume functionality for my audio recording module in Java. So far all I have found on SO is this, which does not give a definitive answer - I have tried the answerer's suggestion of calling start() and stop() on the TargetDataLine to achieve this, and am aware that stop() (from Oracle):



"Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible."



However I am finding that when I call stop on my TargetDataLine, then sleep for five seconds and call start() to reopen it, the recording never resumes. Here is the code:



import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.*;
import javax.sound.sampled.AudioFileFormat.Type;

public class AudioRecorder

static TargetDataLine targetLine = null;
static final long maxRecordingTime = 3600000; // One hour in milliseconds
static Thread recordThread;

public static void main(String[] args)

try

// Initialise audio format settings and setup data line matching format specification

initialiseAudioSettings();

catch (LineUnavailableException e)

e.printStackTrace();


// TEST

startRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to pause recording...");

pauseRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to resume recording...");

resumeRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to stop recording...");

stopRecording();

System.out.println("Recording stopped...(in theory)");

// /TEST


private static void initialiseAudioSettings() throws LineUnavailableException

// Define audio format as:
// Encoding: Linear PCM
// Sample Rate: 44.1 kHz
// Bit Depth: 16-bit
// Channel Format: Stereo
// Data Storage: Signed & Big-Endian

final AudioFormat audioFormat = new AudioFormat(44100, 16, 2, true, true);

// Store format metadata in an Info variable

final DataLine.Info audioFormatInfo = new DataLine.Info(TargetDataLine.class, audioFormat);

if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE))

throw new LineUnavailableException("No microphone has been detected. Please reconnect the microphone and try again.");
else

System.out.println("Microphone detected. Querying target data line...");


// Use metadata to ascertain whether audio format is supported by default input device

if (AudioSystem.isLineSupported(audioFormatInfo) == false)

throw new LineUnavailableException("The default input device does not support the specified audio output format");


// Get a line matching the specified audio format

targetLine = (TargetDataLine)AudioSystem.getLine(audioFormatInfo);

// Instruct the system to allocate resources to the targetLine and switch it on

targetLine.open();

// Prepare line for audio input

targetLine.start();


private static void startRecording()

TimerTask scheduleRecordingEnd = new TimerTask()

public void run()

stopRecording();

;

Timer recordingTimer = new Timer("Recording Timer");

recordingTimer.schedule(scheduleRecordingEnd, maxRecordingTime);

// Setup recording thread

recordThread = new Thread(new Runnable()

@Override
public void run()


// Route audio input stream to target data line

AudioInputStream audioInputStream = new AudioInputStream(targetLine);

// Instantiate output filepath & filename

File outputFile = new File("C:/temp/test.wav");

// Write input audio to output .wav file

try

AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);

catch (IOException e)

e.printStackTrace();



);

// Start recording

recordThread.start();


private static void pauseRecording()

targetLine.stop();


private static void resumeRecording()

targetLine.start();


private static void stopRecording()

// Cease all I/O functions of the line

targetLine.stop();

// Close the line, deallocating system resources and deleting metadata

targetLine.close();

System.out.println("Stopping recording...");

recordThread.stop();




The parts of this code that should be of interest are the tests in main() and the startRecording(), pauseRecording() and resumeRecording() functions, although I have included the code in its entirety for completeness.



Could anyone point me in the right direction as to why this might be happening? Any help would be much appreciated.










share|improve this question






















  • I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

    – Mokarrom Hossain
    yesterday













3












3








3


1






I am trying to implement a pause/resume functionality for my audio recording module in Java. So far all I have found on SO is this, which does not give a definitive answer - I have tried the answerer's suggestion of calling start() and stop() on the TargetDataLine to achieve this, and am aware that stop() (from Oracle):



"Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible."



However I am finding that when I call stop on my TargetDataLine, then sleep for five seconds and call start() to reopen it, the recording never resumes. Here is the code:



import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.*;
import javax.sound.sampled.AudioFileFormat.Type;

public class AudioRecorder

static TargetDataLine targetLine = null;
static final long maxRecordingTime = 3600000; // One hour in milliseconds
static Thread recordThread;

public static void main(String[] args)

try

// Initialise audio format settings and setup data line matching format specification

initialiseAudioSettings();

catch (LineUnavailableException e)

e.printStackTrace();


// TEST

startRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to pause recording...");

pauseRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to resume recording...");

resumeRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to stop recording...");

stopRecording();

System.out.println("Recording stopped...(in theory)");

// /TEST


private static void initialiseAudioSettings() throws LineUnavailableException

// Define audio format as:
// Encoding: Linear PCM
// Sample Rate: 44.1 kHz
// Bit Depth: 16-bit
// Channel Format: Stereo
// Data Storage: Signed & Big-Endian

final AudioFormat audioFormat = new AudioFormat(44100, 16, 2, true, true);

// Store format metadata in an Info variable

final DataLine.Info audioFormatInfo = new DataLine.Info(TargetDataLine.class, audioFormat);

if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE))

throw new LineUnavailableException("No microphone has been detected. Please reconnect the microphone and try again.");
else

System.out.println("Microphone detected. Querying target data line...");


// Use metadata to ascertain whether audio format is supported by default input device

if (AudioSystem.isLineSupported(audioFormatInfo) == false)

throw new LineUnavailableException("The default input device does not support the specified audio output format");


// Get a line matching the specified audio format

targetLine = (TargetDataLine)AudioSystem.getLine(audioFormatInfo);

// Instruct the system to allocate resources to the targetLine and switch it on

targetLine.open();

// Prepare line for audio input

targetLine.start();


private static void startRecording()

TimerTask scheduleRecordingEnd = new TimerTask()

public void run()

stopRecording();

;

Timer recordingTimer = new Timer("Recording Timer");

recordingTimer.schedule(scheduleRecordingEnd, maxRecordingTime);

// Setup recording thread

recordThread = new Thread(new Runnable()

@Override
public void run()


// Route audio input stream to target data line

AudioInputStream audioInputStream = new AudioInputStream(targetLine);

// Instantiate output filepath & filename

File outputFile = new File("C:/temp/test.wav");

// Write input audio to output .wav file

try

AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);

catch (IOException e)

e.printStackTrace();



);

// Start recording

recordThread.start();


private static void pauseRecording()

targetLine.stop();


private static void resumeRecording()

targetLine.start();


private static void stopRecording()

// Cease all I/O functions of the line

targetLine.stop();

// Close the line, deallocating system resources and deleting metadata

targetLine.close();

System.out.println("Stopping recording...");

recordThread.stop();




The parts of this code that should be of interest are the tests in main() and the startRecording(), pauseRecording() and resumeRecording() functions, although I have included the code in its entirety for completeness.



Could anyone point me in the right direction as to why this might be happening? Any help would be much appreciated.










share|improve this question














I am trying to implement a pause/resume functionality for my audio recording module in Java. So far all I have found on SO is this, which does not give a definitive answer - I have tried the answerer's suggestion of calling start() and stop() on the TargetDataLine to achieve this, and am aware that stop() (from Oracle):



"Stops the line. A stopped line should cease I/O activity. If the line is open and running, however, it should retain the resources required to resume activity. A stopped line should retain any audio data in its buffer instead of discarding it, so that upon resumption the I/O can continue where it left off, if possible."



However I am finding that when I call stop on my TargetDataLine, then sleep for five seconds and call start() to reopen it, the recording never resumes. Here is the code:



import java.io.*;
import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.*;
import javax.sound.sampled.AudioFileFormat.Type;

public class AudioRecorder

static TargetDataLine targetLine = null;
static final long maxRecordingTime = 3600000; // One hour in milliseconds
static Thread recordThread;

public static void main(String[] args)

try

// Initialise audio format settings and setup data line matching format specification

initialiseAudioSettings();

catch (LineUnavailableException e)

e.printStackTrace();


// TEST

startRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to pause recording...");

pauseRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to resume recording...");

resumeRecording();

try

System.out.println("Sleeping for 5s...");
Thread.sleep(5000);

catch (InterruptedException e)

e.printStackTrace();


System.out.println("About to stop recording...");

stopRecording();

System.out.println("Recording stopped...(in theory)");

// /TEST


private static void initialiseAudioSettings() throws LineUnavailableException

// Define audio format as:
// Encoding: Linear PCM
// Sample Rate: 44.1 kHz
// Bit Depth: 16-bit
// Channel Format: Stereo
// Data Storage: Signed & Big-Endian

final AudioFormat audioFormat = new AudioFormat(44100, 16, 2, true, true);

// Store format metadata in an Info variable

final DataLine.Info audioFormatInfo = new DataLine.Info(TargetDataLine.class, audioFormat);

if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE))

throw new LineUnavailableException("No microphone has been detected. Please reconnect the microphone and try again.");
else

System.out.println("Microphone detected. Querying target data line...");


// Use metadata to ascertain whether audio format is supported by default input device

if (AudioSystem.isLineSupported(audioFormatInfo) == false)

throw new LineUnavailableException("The default input device does not support the specified audio output format");


// Get a line matching the specified audio format

targetLine = (TargetDataLine)AudioSystem.getLine(audioFormatInfo);

// Instruct the system to allocate resources to the targetLine and switch it on

targetLine.open();

// Prepare line for audio input

targetLine.start();


private static void startRecording()

TimerTask scheduleRecordingEnd = new TimerTask()

public void run()

stopRecording();

;

Timer recordingTimer = new Timer("Recording Timer");

recordingTimer.schedule(scheduleRecordingEnd, maxRecordingTime);

// Setup recording thread

recordThread = new Thread(new Runnable()

@Override
public void run()


// Route audio input stream to target data line

AudioInputStream audioInputStream = new AudioInputStream(targetLine);

// Instantiate output filepath & filename

File outputFile = new File("C:/temp/test.wav");

// Write input audio to output .wav file

try

AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);

catch (IOException e)

e.printStackTrace();



);

// Start recording

recordThread.start();


private static void pauseRecording()

targetLine.stop();


private static void resumeRecording()

targetLine.start();


private static void stopRecording()

// Cease all I/O functions of the line

targetLine.stop();

// Close the line, deallocating system resources and deleting metadata

targetLine.close();

System.out.println("Stopping recording...");

recordThread.stop();




The parts of this code that should be of interest are the tests in main() and the startRecording(), pauseRecording() and resumeRecording() functions, although I have included the code in its entirety for completeness.



Could anyone point me in the right direction as to why this might be happening? Any help would be much appreciated.







java audio playback recording pause






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 6 at 13:35









Louis CowellLouis Cowell

5510




5510












  • I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

    – Mokarrom Hossain
    yesterday

















  • I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

    – Mokarrom Hossain
    yesterday
















I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

– Mokarrom Hossain
yesterday





I guess API doesn't provide any straight forward way to do that. Try to append at the end of an existing file. Check other overloaded write() method in AudioSystem. You need to re-run your recordThread, in your code, it's just executed only once.

– Mokarrom Hossain
yesterday












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55024401%2fpausing-audio-recording-in-java%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55024401%2fpausing-audio-recording-in-java%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович