Record sound: Difference between revisions
Content deleted Content added
m →{{header|Phix}}: syntax coloured, marked p2js incompatible |
Initial submission |
||
(16 intermediate revisions by 7 users not shown) | |||
Line 19:
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs might not record sound in the same format.)
=={{header|Ada}}==
{{libheader|ASFML}}
<syntaxhighlight lang="ada">
with Sf.Audio.SoundBufferRecorder;
with Sf.Audio.SoundBuffer;
with Ada.Text_IO;
procedure Record_Sound is
use Sf, Sf.Audio, Ada.Text_IO;
Sound_Buffer_Recorder : constant sfSoundBufferRecorder_Ptr := SoundBufferRecorder.create;
Sound_Buffer : sfSoundBuffer_Ptr;
begin
if Sound_Buffer_Recorder = null then
Put_Line (Standard_Error, "Error: sound recorder not available!");
return;
end if;
-- By default the recording is in 16-bit mono. Using the
-- setChannelCount method you can change the number of channels
-- used by the audio capture device to record.
if SoundBufferRecorder.start (Sound_Buffer_Recorder, sampleRate => 44_100) /= sfTrue then
Put_Line (Standard_Error, "Error: sound recorder cannot start!");
return;
end if;
delay 10.0;
SoundBufferRecorder.stop (Sound_Buffer_Recorder);
Sound_Buffer := SoundBufferRecorder.getBuffer (Sound_Buffer_Recorder);
if SoundBuffer.saveToFile (Sound_Buffer, filename => "output.ogg") /= sfTrue then
Put_Line (Standard_Error, "Error: recorded sound could not be saved!");
end if;
SoundBufferRecorder.destroy (Sound_Buffer_Recorder);
end Record_Sound;
</syntaxhighlight>
=={{header|AutoHotkey}}==
<
waitsec := 5
Tooltip Recording %name%.wav
Line 56 ⟶ 95:
; 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</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
bitspersample% = 16
channels% = 2
Line 95 ⟶ 134:
SYS "mciSendString", "close capture", 0, 0, 0
PRINT "Captured audio is stored in " wavfile$</
{{omit from|Batch File}}
Line 103 ⟶ 142:
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.
<
#include <unistd.h>
#include <sys/types.h>
Line 132 ⟶ 171:
play(p, 65536);
return 0;
}</
=={{header|C++}}==
Uses Windows MCI
<
#include <iostream>
#include <string>
Line 230 ⟶ 269:
return 0;
}
</syntaxhighlight>
=={{header|ChucK}}==
<
// example> chuck foo.ck bar.ck rec
Line 256 ⟶ 295:
// infinite time loop...
// ctrl-c will stop it, or modify to desired duration
while( true ) 1::second => now;</
=={{header|Common Lisp}}==
{{trans|C}}
<
(defun record (n)
(with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8))
Line 272 ⟶ 311:
)
(play (record 65536))
</syntaxhighlight>
=={{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|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
// ---------------
include "NSLog.incl"
include "Tlbx Speech.incl"
include "Tlbx AVFoundation.incl"
output "RecordToTextDemo"
#plist CFBundleIdentifier @"com.futurebasic.RecordToTextDemo"
#plist NSSpeechRecognitionUsageDescription @"Enable speech recognition."
#plist NSMicrophoneUsageDescription @"This app requires microphone access."
#define FILE_URL fn URLByAppendingPathComponent(fn FileManagerURLForApplicationDirectory,@"MyAudioFile.m4a")
#define RECORDER_KEY @"recorder"
_window = 1
begin enum 1
_recordBtn
end enum
void local fn FixViews
dispatchmain
AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY )
if ( recorder )
button _recordBtn,,, @"Stop Recording",,,, _window
else
button _recordBtn,,, @"Start Recording",,,, _window
end if
dispatchend
end fn
void local fn BuildWindow
window _window, @"Record Demo", (0,0,480,270)
button _recordBtn,,, @"Start Recording", (13,13,129,32)
end fn
void local fn MyRecognitionTaskHandler( ref as SFSpeechRecognizerRef, result as SFSpeechRecognitionResultRef, err as ErrorRef, userData as ptr )
SFTranscriptionRef transcription = fn SFSpeechRecognitionResultBestTranscription( result )
if ( err )
NSLog(@"error")
else
if ( fn SFSpeechRecognitionResultIsFinal( result ) )
NSLog(@"%@",fn SFTranscriptionFormattedString( transcription ))
end if
end if
end fn
void local fn MyRequestAuthorization( status as SFSpeechRecognizerAuthorizationStatus, userData as ptr )
SFSpeechRecognizerRef recognizer
SFSpeechURLRecognitionRequestRef request
select ( status )
case SFSpeechRecognizerAuthorizationStatusNotDetermined : NSLog(@"Authorization not determined")
case SFSpeechRecognizerAuthorizationStatusDenied : NSLog(@"Authorization denied")
case SFSpeechRecognizerAuthorizationStatusRestricted : NSLog(@"Authorization restricted")
case SFSpeechRecognizerAuthorizationStatusAuthorized
recognizer = fn SFSpeechRecognizerInit
if ( fn SFSpeechRecognizerIsAvailable( recognizer ) )
if ( FILE_URL )
fn SoundPlay( fn SoundWithContentsOfURL( FILE_URL, YES ) )
request = fn SFSpeechURLRecognitionRequestWithURL( FILE_URL )
SFSpeechRecognizerSetSupportsOnDeviceRecognition( recognizer, YES )
fn SFSpeechRecognizerRecognitionTaskWithResultHandler( recognizer, request, @fn MyRecognitionTaskHandler, NULL )
end if
else
NSLog(@"Speech recognizer not available")
end if
end select
end fn
void local fn RecognizeSpeech
SFSpeechRecognizerRequestAuthorization( @fn MyRequestAuthorization, NULL )
end fn
void local fn RecordAudio
CFDictionaryRef settings = @{
AVFormatIDKey:@(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey:@(AVAudioQualityHigh),
AVSampleRateKey:@44100.0,
AVNumberOfChannelsKey:@1,
AVLinearPCMBitDepthKey:@16}
AVAudioFormatRef format = fn AVAudioFormatWithSettings( settings )
AVAudioRecorderRef recorder = fn AVAudioRecorderWithFormat( FILE_URL, format, NULL )
AppSetProperty( RECORDER_KEY, recorder )
fn FixViews
fn AVAudioRecorderRecord( recorder )
end fn
void local fn MyRequestAccessHandler( granted as BOOL, userData as ptr )
if ( granted ) then fn RecordAudio
end fn
void local fn StartStopRecording
AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY )
AVAuthorizationStatus status
if ( recorder )
AVAudioRecorderStop( recorder )
AppRemoveProperty( RECORDER_KEY )
fn FixViews
fn RecognizeSpeech
else
status = fn AVCaptureDeviceAuthorizationStatus( AVMediaTypeAudio )
select ( status )
case AVAuthorizationStatusDenied : NSLog(@"Denied")
case AVAuthorizationStatusRestricted : NSLog(@"Restricted")
case AVAuthorizationStatusAuthorized : fn RecordAudio
case AVAuthorizationStatusNotDetermined
AVCaptureDeviceRequestAccess( AVMediaTypeAudio, @fn MyRequestAccessHandler, NULL )
end select
end if
end fn
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _recordBtn : fn StartStopRecording
end select
end select
end fn
fn BuildWindow
on dialog fn DoDialog
HandleEvents
</syntaxhighlight>
=={{header|Go}}==
Line 280 ⟶ 558:
The file name, sampling rate and duration can all be set by the user.
<
import (
Line 340 ⟶ 618:
check(err)
fmt.Println("Play-back completed.")
}</
=={{header|GUISS}}==
Line 346 ⟶ 624:
Here we activate the Microsoft Windows '95 Sound Recorder:
<
=={{header|Java}}==
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.*;
public final class SoundRecorder {
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">
using PortAudio, LibSndFile
Line 355 ⟶ 702:
buf = read(stream, 441000)
save("recorded10sec.wav", buf)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Scala}}
<
import java.io.File
Line 403 ⟶ 750:
println(lue.message)
}
}</
=={{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">
run "sndrec32.exe"
</syntaxhighlight>
A more direct way is..
<syntaxhighlight lang="lb">
print "Starting 5 sec. recording..."
r$ =mciSendString$( "open new type waveaudio alias capture")
Line 446 ⟶ 793:
end if
end function
</syntaxhighlight>
=={{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.<
set the dontUseQT to false -- on windows use true
set the recordFormat to "wave" -- can be wav,aiff, au
Line 461 ⟶ 808:
stop recording
end if
end makeRecording</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|Nim}}==
Line 470 ⟶ 817:
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.
<
var name = ""
Line 497 ⟶ 844:
echo "'$1' created on disk and will now be played back..." % name
echo execProcess("aplay", args = [name], options = {poStdErrToStdOut, poUsePath})
echo "Playback completed"</
=={{header|OCaml}}==
{{trans|C}}
<
let record bytes =
Line 522 ⟶ 869:
let bytes = 65536 in
let p = record bytes in
play p bytes</
=={{header|Phix}}==
Line 528 ⟶ 875:
{{trans|C}}
{{trans|Go}}
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Record_sound.exw
Line 613 ⟶ 960:
-- printf(1,"Play-back completed.\n")</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
=={{header|PicoLisp}}==
<
(make
(while (rd 2)
(link @) ) ) )</
Output:
Line 627 ⟶ 974:
=={{header|Python}}==
<
chunk = 1024
Line 643 ⟶ 990:
data = stream.read(chunk)
print [ord(i) for i in data]</
=={{header|Racket}}==
{{trans|C}}
<
#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>
=={{header|Raku}}==
(formerly Perl 6)
Slightly modified from an example provided with the <code>Audio::PortAudio</code> module distribution.
<syntaxhighlight lang="raku"
use Audio::Sndfile;
Line 725 ⟶ 1,072:
}
}</
=={{header|Scala}}==
{{libheader|Scala}}
<
import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream}
import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine}
Line 779 ⟶ 1,126:
case ioe: IOException => ioe.printStackTrace()
}
}</
=={{header|Tcl}}==
{{libheader|Snack}}<
# Helper to do a responsive wait
Line 800 ⟶ 1,147:
# Destroy the recording object
$recording destroy</
=={{header|Wee Basic}}==
<
micrec
print 1 "Playing..."
micpla
end</
=={{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.
<
class C {
Line 850 ⟶ 1,197:
System.print("\n'%(name)' created on disk and will now be played back...")
C.aplay(name)
System.print("\nPlay-back completed.")</
<br>
We now embed this in the following C program, compile and run it.
<
#include <stdio_ext.h>
#include <stdlib.h>
Line 938 ⟶ 1,285:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 954 ⟶ 1,301:
free(script);
return 0;
}</
|