阅读量:0
在Java中实现声音的录制与播放可以使用JavaSound API。以下是一个简单的示例代码:
录制声音:
import javax.sound.sampled.*; public class AudioRecorder { public static void main(String[] args) { try { AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format); line.start(); AudioInputStream ais = new AudioInputStream(line); AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("audio.wav")); line.stop(); line.close(); } catch (LineUnavailableException | IOException e) { e.printStackTrace(); } } }
播放声音:
import javax.sound.sampled.*; public class AudioPlayer { public static void main(String[] args) { try { AudioInputStream ais = AudioSystem.getAudioInputStream(new File("audio.wav")); AudioFormat format = ais.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); byte[] data = new byte[1024]; int bytesRead = 0; while ((bytesRead = ais.read(data, 0, data.length)) != -1) { line.write(data, 0, bytesRead); } line.drain(); line.close(); } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) { e.printStackTrace(); } } }
在上面的示例代码中,AudioRecorder
类实现了声音的录制,将录制的声音保存为一个WAV文件;AudioPlayer
类实现了声音的播放,从录制的WAV文件中读取声音数据并进行播放。