Я написал следующий скрипт на Java, который предназначен для записи нескольких секунд звука с микрофона.
Проблема в том, что он хочет записывать только внутренний микрофон ноутбука, а не внешний USB-микрофон. .
USB-микрофон корректно записан с помощью аналогичного Python-скрипта, а значит, его можно обнаружить и он полностью работоспособен.
import javax.sound.sampled.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Timer;
import java.util.TimerTask;
public class SimpleAudioRecorder {
private static final float SAMPLE_RATE = 44100; // Audio sample rate
private static final int BUFFER_SIZE = 4096; // Buffer size for audio recording
private static final float GAIN_FACTOR = 1.0f; // Amplification factor for microphone input (adjusted)
private static final File OUTPUT_FILE = new File("recording.wav"); // Output file path
private static final int RECORD_DURATION_MS = 5000; // Record duration in milliseconds (5 seconds)
private static TargetDataLine microphone;
private static volatile boolean recordingStopped = false; // Flag to indicate if recording is stopped
public static void main(String[] args) {
try {
// Initialize audio components
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 2, true, true);
initializeMicrophone(format);
startRecording();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initializeMicrophone(AudioFormat format) {
try {
// Get and open the microphone
DataLine.Info micInfo = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(micInfo)) {
System.err.println("Microphone not supported");
System.exit(0);
}
microphone = (TargetDataLine) AudioSystem.getLine(micInfo);
microphone.open(format);
System.out.println("Microphone initialized and opened.");
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void startRecording() {
System.out.println("Recording started!");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Set up a timer to stop recording after 5 seconds
Timer stopTimer = new Timer();
stopTimer.schedule(new TimerTask() {
@Override
public void run() {
stopRecording(); // Stop the recording after 5 seconds
saveRecording(outputStream); // Save the recording
}
}, RECORD_DURATION_MS);
microphone.start();
System.out.println("Microphone started.");
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
// Record audio
while (!recordingStopped) {
bytesRead = microphone.read(buffer, 0, buffer.length);
if (bytesRead > 0) {
// Amplify the audio data correctly by scaling up each sample
for (int i = 0; i < bytesRead - 1; i += 2) {
// Convert byte pair (little-endian) into a 16-bit signed sample
short sample = (short) ((buffer[i + 1] > 8);
}
outputStream.write(buffer, 0, bytesRead);
}
}
// Stop and close the microphone
microphone.stop();
microphone.close();
System.out.println("Microphone stopped and closed.");
}
private static void saveRecording(ByteArrayOutputStream outputStream) {
try {
// Save the recorded audio to a file
byte[] audioData = outputStream.toByteArray();
saveAudioToFile(audioData, new AudioFormat(SAMPLE_RATE, 16, 2, true, true));
System.out.println("Recording saved to " + OUTPUT_FILE.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void saveAudioToFile(byte[] audioData, AudioFormat format) throws IOException {
byte[] normalizedAudioData = normalizeVolume(audioData);
try (FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
AudioInputStream audioInputStream = new AudioInputStream(
new ByteArrayInputStream(normalizedAudioData), format, normalizedAudioData.length / format.getFrameSize());
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, bos);
}
}
private static byte[] normalizeVolume(byte[] audioData) {
short[] audioDataShort = new short[audioData.length / 2];
ByteBuffer.wrap(audioData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(audioDataShort);
// Find the maximum absolute value
int max = 0; // Change type to int
for (short sample : audioDataShort) {
int absSample = Math.abs(sample); // Convert to int for abs calculation
if (absSample > max) {
max = absSample;
}
}
// Calculate normalization factor
float normalizationFactor = 32767.0f / max;
// Apply normalization
for (int i = 0; i < audioDataShort.length; i++) {
audioDataShort = (short) Math.min(Math.max(audioDataShort * normalizationFactor, Short.MIN_VALUE), Short.MAX_VALUE);
}
ByteBuffer byteBuffer = ByteBuffer.allocate(audioDataShort.length * 2).order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
shortBuffer.put(audioDataShort);
return byteBuffer.array();
}
private static void stopRecording() {
System.out.println("Stopping recording...");
recordingStopped = true; // Set flag to true to stop recording
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... laptop-mic
Я не могу создать код для записи с USB-микрофона; записывается только внутренний микрофон ноутбука ⇐ JAVA
Программисты JAVA общаются здесь
1728054739
Anonymous
Я написал следующий скрипт на Java, который предназначен для записи нескольких секунд звука с микрофона.
Проблема в том, что он хочет записывать только внутренний микрофон ноутбука, а не внешний USB-микрофон. .
USB-микрофон корректно записан с помощью аналогичного Python-скрипта, а значит, его можно обнаружить и он полностью работоспособен.
import javax.sound.sampled.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Timer;
import java.util.TimerTask;
public class SimpleAudioRecorder {
private static final float SAMPLE_RATE = 44100; // Audio sample rate
private static final int BUFFER_SIZE = 4096; // Buffer size for audio recording
private static final float GAIN_FACTOR = 1.0f; // Amplification factor for microphone input (adjusted)
private static final File OUTPUT_FILE = new File("recording.wav"); // Output file path
private static final int RECORD_DURATION_MS = 5000; // Record duration in milliseconds (5 seconds)
private static TargetDataLine microphone;
private static volatile boolean recordingStopped = false; // Flag to indicate if recording is stopped
public static void main(String[] args) {
try {
// Initialize audio components
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 2, true, true);
initializeMicrophone(format);
startRecording();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initializeMicrophone(AudioFormat format) {
try {
// Get and open the microphone
DataLine.Info micInfo = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(micInfo)) {
System.err.println("Microphone not supported");
System.exit(0);
}
microphone = (TargetDataLine) AudioSystem.getLine(micInfo);
microphone.open(format);
System.out.println("Microphone initialized and opened.");
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void startRecording() {
System.out.println("Recording started!");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Set up a timer to stop recording after 5 seconds
Timer stopTimer = new Timer();
stopTimer.schedule(new TimerTask() {
@Override
public void run() {
stopRecording(); // Stop the recording after 5 seconds
saveRecording(outputStream); // Save the recording
}
}, RECORD_DURATION_MS);
microphone.start();
System.out.println("Microphone started.");
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
// Record audio
while (!recordingStopped) {
bytesRead = microphone.read(buffer, 0, buffer.length);
if (bytesRead > 0) {
// Amplify the audio data correctly by scaling up each sample
for (int i = 0; i < bytesRead - 1; i += 2) {
// Convert byte pair (little-endian) into a 16-bit signed sample
short sample = (short) ((buffer[i + 1] > 8);
}
outputStream.write(buffer, 0, bytesRead);
}
}
// Stop and close the microphone
microphone.stop();
microphone.close();
System.out.println("Microphone stopped and closed.");
}
private static void saveRecording(ByteArrayOutputStream outputStream) {
try {
// Save the recorded audio to a file
byte[] audioData = outputStream.toByteArray();
saveAudioToFile(audioData, new AudioFormat(SAMPLE_RATE, 16, 2, true, true));
System.out.println("Recording saved to " + OUTPUT_FILE.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void saveAudioToFile(byte[] audioData, AudioFormat format) throws IOException {
byte[] normalizedAudioData = normalizeVolume(audioData);
try (FileOutputStream fos = new FileOutputStream(OUTPUT_FILE);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
AudioInputStream audioInputStream = new AudioInputStream(
new ByteArrayInputStream(normalizedAudioData), format, normalizedAudioData.length / format.getFrameSize());
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, bos);
}
}
private static byte[] normalizeVolume(byte[] audioData) {
short[] audioDataShort = new short[audioData.length / 2];
ByteBuffer.wrap(audioData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(audioDataShort);
// Find the maximum absolute value
int max = 0; // Change type to int
for (short sample : audioDataShort) {
int absSample = Math.abs(sample); // Convert to int for abs calculation
if (absSample > max) {
max = absSample;
}
}
// Calculate normalization factor
float normalizationFactor = 32767.0f / max;
// Apply normalization
for (int i = 0; i < audioDataShort.length; i++) {
audioDataShort[i] = (short) Math.min(Math.max(audioDataShort[i] * normalizationFactor, Short.MIN_VALUE), Short.MAX_VALUE);
}
ByteBuffer byteBuffer = ByteBuffer.allocate(audioDataShort.length * 2).order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer shortBuffer = byteBuffer.asShortBuffer();
shortBuffer.put(audioDataShort);
return byteBuffer.array();
}
private static void stopRecording() {
System.out.println("Stopping recording...");
recordingStopped = true; // Set flag to true to stop recording
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79054844/i-cannot-make-code-to-record-from-a-usb-microphone-only-the-internal-laptop-mic[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия