Record sound: Difference between revisions

sort
(sort)
(11 intermediate revisions by 5 users not shown)
Line 21:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">name := "sample"
waitsec := 5
Tooltip Recording %name%.wav
Line 56:
; For more intuitive functions, see the MCI library by jballi.
; doc: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.html
; download: http://www.autohotkey.net/~jballi/MCI/v1.1/MCI.ahk</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> wavfile$ = @dir$ + "capture.wav"
bitspersample% = 16
channels% = 2
Line 95:
SYS "mciSendString", "close capture", 0, 0, 0
PRINT "Captured audio is stored in " wavfile$</langsyntaxhighlight>
 
{{omit from|Batch File}}
Line 103:
Read/write raw device <code>/dev/dsp</code>. On Linux you need access to said device, meaning probably you should be in audio user group.
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
Line 132:
play(p, 65536);
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses Windows MCI
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <string>
Line 230:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|ChucK}}==
 
<langsyntaxhighlight lang="c">// chuck this with other shreds to record to file
// example> chuck foo.ck bar.ck rec
 
Line 256:
// infinite time loop...
// ctrl-c will stop it, or modify to desired duration
while( true ) 1::second => now;</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
{{trans|C}}
<langsyntaxhighlight lang="lisp">
(defun record (n)
(with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8))
Line 272:
)
(play (record 65536))
</syntaxhighlight>
</lang>
 
=={{header|Diego}}==
This <code>funct</code>ion returns a <code>{wav}</code> variable recorded from a thing in the mist. It understands that the found <code>thing</code> has a microphone, so will have microphone knowledge. If the caller does not have microphone knowledge, the callee will train the caller on first request.
<syntaxhighlight lang="diego">begin_funct({wav}, Record sound);
set_decision(linger);
find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)
? with_found()_microphone()_label(mic);
: err_funct[]_err(Sorry, no one has a microphone!);
exit_funct[];
;
with_microphone[mic]_record()_durat({secs}, 30)_var(recording);
[Record sound]_ret([recording]);
reset_decision();
end_funct[];
 
// Record a monophonic 16-bit PCM sound into memory space:
exec_funct(Record sound)_var(PCMRecording)_me(); // The variable 'PCMRecording' is the sound in memory space
 
// Record a monophonic 16-bit PCM sound into a file or array:
exec_funct(Record sound)_file(foo.wav)_me(); // The file 'foo.wav' is the sound in a file</syntaxhighlight>
 
This is the <code>instruct</code>ion version, where the thing keeps the recording.
<syntaxhighlight lang="diego">begin_instruct(Record sound);
set_decision(linger);
find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)
? with_found()_label(recorder)_microphone()_label(mic);
: err_instruct[]_err(Sorry, no one has a microphone!);
exit_instruct[];
;
with_microphone[mic]_record()_durat({secs}, 30)_var(recording);
reset_decision();
end_instruct[];
 
// Record a monophonic 16-bit PCM sound into memory space:
exec_instruct(Record sound)_me();
with_thing[recorder]_microphone[mic]_var[recording]_var(PCMRecording); // The variable 'PCMRecording' is the sound in memory space
 
// Record a monophonic 16-bit PCM sound into a file or array:
exec_instruct(Record sound)_me();
with_thing[recorder]_microphone[mic]_var[recording]_file(foo.wav)_me(); // The file 'foo.wav' is the sound in a file</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="vbnet">#define PI 4 * Atn(1)
 
' Constants for the audio format
Dim Shared As Integer SAMPLE_RATE = 44100
Dim Shared As Integer BITS_PER_SAMPLE = 16
Dim Shared As Integer NUM_CHANNELS = 1
 
' Generates a sine wave
Sub generateSineWave(buffer() As Short, frequency As Double)
Dim As Double increment = 2.0 * PI * frequency / SAMPLE_RATE
Dim As Double x = 0.0
For i As Integer = 0 To Ubound(buffer)
buffer(i) = (Sin(x) * 32767.0)
x += increment
Next i
End Sub
 
' Write the header of the .wav file
Sub writeWaveHeader(file As Integer, numSamples As Integer)
' Write the RIFF header
Print #file, "RIFF";
Put #file, , numSamples * 2 + 36 ' File size
Print #file, "WAVE";
Dim As Integer SB = 16, FA = 1
' Write the fmt sub-block
Print #file, "fmt ";
Put #file, , SB ' Size of the fmt sub-block
Put #file, , FA ' Audio format (1 = PCM)
Put #file, , NUM_CHANNELS ' Number of channels
Put #file, , SAMPLE_RATE ' Sample rate
Put #file, , SAMPLE_RATE * NUM_CHANNELS * BITS_PER_SAMPLE / 8 ' Byte rate
Put #file, , NUM_CHANNELS * BITS_PER_SAMPLE / 8 ' Alineación de bloques
Put #file, , BITS_PER_SAMPLE ' Bits per sample
' Write the data sub-block
Print #file, "data";
Put #file, , numSamples * 2 ' Data size
End Sub
 
Dim As Integer file = Freefile
Open "output.wav" For Binary As #file
 
' Generates a 440 Hz sine wave for 5 seconds
Dim As Integer numSamples = SAMPLE_RATE * 5
Dim As Short buffer(numSamples - 1)
generateSineWave(buffer(), 440.0)
 
' Write the .wav file
writeWaveHeader(file, numSamples)
Put #file, , buffer()
 
Close #file</syntaxhighlight>
 
=={{header|Go}}==
Line 280 ⟶ 375:
 
The file name, sampling rate and duration can all be set by the user.
<langsyntaxhighlight lang="go">package main
 
import (
Line 340 ⟶ 435:
check(err)
fmt.Println("Play-back completed.")
}</langsyntaxhighlight>
 
=={{header|DiegoGUISS}}==
This <code>instruct</code>ion understands that the found <code>thing</code> has a microphone, so will have microphone knowledge. If the caller does not have microphone knowledge, the callee will train the caller on first request.
<lang diego>begin_funct({wav}, Record sound);
set_decision(linger);
find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)
? with_found()_label(recorder)_microphone()_label(mic);
: err_instruct[]_err(Sorry, no one has a microphone!);
exit_instruct[];
;
with_microphone[mic]_record()_durat({secs}, 30)_var(recording);
[Record sound]_ret([recording]);
reset_decision();
end_funct[];
 
Here we activate the Microsoft Windows '95 Sound Recorder:
// Record a monophonic 16-bit PCM sound into memory space:
exec_funct(Record sound)_var(PCMRecording)_me(); // The variable 'PCMRecording' is the sound in memory space
 
<syntaxhighlight lang="guiss">Start,Programs,Accessories,Sound Recorder,Button:Record</syntaxhighlight>
// Record a monophonic 16-bit PCM sound into a file or array:
exec_funct(Record sound)_file(foo.wav)_me(); // The file 'foo.wav' is the sound in a file</lang>
 
=={{header|GUISSJava}}==
Java can record sound without external libraries.
<syntaxhighlight lang="java">
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.io.File;
 
import javax.sound.sampled.AudioFileFormat.*;
Here we activate the Microsoft Windows '95 Sound Recorder:
 
public final class SoundRecorder {
<lang guiss>Start,Programs,Accessories,Sound Recorder,Button:Record</lang>
 
public static void main(String[] args) {
SoundRecorder recorder = new SoundRecorder();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule( () -> recorder.finish(), 10, TimeUnit.SECONDS);
scheduler.shutdown();
 
recorder.start();
}
private void start() {
try {
AudioFormat format = createAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if ( ! AudioSystem.isLineSupported(info) ) {
System.out.println("Data line format is not supported");
Runtime.getRuntime().exit(0);
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
System.out.println("Starting to capture and record audio");
AudioInputStream audioInputStream = new AudioInputStream(line);
AudioSystem.write(audioInputStream, audioFileType, wavFile);
} catch (LineUnavailableException | IOException exception) {
exception.printStackTrace(System.err);
}
}
 
private AudioFormat createAudioFormat() {
final float sampleRate = 16_000.0F;
final int sampleSizeInBits = 16;
final int channels = 1;
final boolean signed = true;
final boolean bigEndian = true;
// Monophonic 16-bit PCM audio format
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
}
 
private void finish() {
line.stop();
line.close();
System.out.println("Finished capturing and recording audio");
}
private TargetDataLine line;
private final File wavFile = new File("SoundRecorder.wav");
private final AudioFileFormat.Type audioFileType = AudioFileFormat.Type.WAVE;
}</syntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
using PortAudio, LibSndFile
 
Line 375 ⟶ 519:
buf = read(stream, 441000)
save("recorded10sec.wav", buf)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Scala}}
<langsyntaxhighlight lang="scala">// version 1.1.3
 
import java.io.File
Line 423 ⟶ 567:
println(lue.message)
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
LB can easily send a MCI string to the OS, or extra routines eg SOX, so a minimal solution could be
<syntaxhighlight lang="lb">
<lang lb>
run "sndrec32.exe"
</syntaxhighlight>
</lang>
A more direct way is..
<syntaxhighlight lang="lb">
<lang lb>
print "Starting 5 sec. recording..."
r$ =mciSendString$( "open new type waveaudio alias capture")
Line 466 ⟶ 610:
end if
end function
</syntaxhighlight>
</lang>
 
=={{header|LiveCode}}==
This example sets some aspects of a sound recording individually and also shows use of the sound input dialog where a user can conveniently set them as well, either may be used.<langsyntaxhighlight LiveCodelang="livecode">command makeRecording
set the dontUseQT to false -- on windows use true
set the recordFormat to "wave" -- can be wav,aiff, au
Line 481 ⟶ 625:
stop recording
end if
end makeRecording</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">SystemDialogInput["RecordSound"]</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 490 ⟶ 634:
This code is for Linux systems and uses “arecord” and “aplay”. Previous code which used “/dev/dsp” no longer works on modern OS.
This code is a direct translation from Go version, but uses integers instead of floats for duration.
<langsyntaxhighlight lang="nim">import osproc, strutils
 
var name = ""
Line 517 ⟶ 661:
echo "'$1' created on disk and will now be played back..." % name
echo execProcess("aplay", args = [name], options = {poStdErrToStdOut, poUsePath})
echo "Playback completed"</langsyntaxhighlight>
 
=={{header|OCaml}}==
{{trans|C}}
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma"
let record bytes =
Line 542 ⟶ 686:
let bytes = 65536 in
let p = record bytes in
play p bytes</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 548 ⟶ 692:
{{trans|C}}
{{trans|Go}}
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Record_sound.exw
Line 633 ⟶ 777:
-- printf(1,"Play-back completed.\n")</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PicoLisp}}==
 
<langsyntaxhighlight PicoLisplang="picolisp">(in '(rec -q -c1 -tu16 - trim 0 2) # Record 2 seconds
(make
(while (rd 2)
(link @) ) ) )</langsyntaxhighlight>
 
Output:
Line 647 ⟶ 791:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">import pyaudio
 
chunk = 1024
Line 663 ⟶ 807:
 
data = stream.read(chunk)
print [ord(i) for i in data]</langsyntaxhighlight>
 
=={{header|Racket}}==
{{trans|C}}
<langsyntaxhighlight lang="racket">
#lang racket
(define (record n) (with-input-from-file "/dev/dsp" ( () (read-bytes n))))
(define (play bs) (display-to-file bs "/dev/dsp" #:exists 'append))
(play (record 65536))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Slightly modified from an example provided with the <code>Audio::PortAudio</code> module distribution.
<syntaxhighlight lang="raku" perl6line>use Audio::PortAudio;
use Audio::Sndfile;
 
Line 745 ⟶ 889:
}
 
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import java.io.{File, IOException}
import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream}
import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine}
Line 799 ⟶ 943:
case ioe: IOException => ioe.printStackTrace()
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Snack}}<langsyntaxhighlight lang="tcl">package require sound
 
# Helper to do a responsive wait
Line 820 ⟶ 964:
 
# Destroy the recording object
$recording destroy</langsyntaxhighlight>
 
=={{header|Wee Basic}}==
<langsyntaxhighlight Weelang="wee Basicbasic">print 1 "Recording..."
micrec
print 1 "Playing..."
micpla
end</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
The ability to call external processes such as ''arecord'' is expected to be added to Wren-cli in the next release. In the meantime, we embed the following Wren script in a C host to complete this task.
<langsyntaxhighlight ecmascriptlang="wren">/* record_soundRecord_sound.wren */
 
class C {
Line 870 ⟶ 1,014:
System.print("\n'%(name)' created on disk and will now be played back...")
C.aplay(name)
System.print("\nPlay-back completed.")</langsyntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
Line 958 ⟶ 1,102:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "record_soundRecord_sound.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 974 ⟶ 1,118:
free(script);
return 0;
}</langsyntaxhighlight>
62

edits