Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Terminal control/Ringing the terminal bell

From Rosetta Code
<Terminal control
Task
Terminal control/Ringing the terminal bell
You are encouraged tosolve this task according to the task description, using any language you may know.


Task

Make the terminal running the program ring its "bell".


On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usually used to indicate a problem where a wrong character has been typed.

In most terminals, if the  Bell character   (ASCII code7,   \a in C)   is printed by the program, it will cause the terminal to ring its bell.   This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.

11l

print("\a")

6800 Assembly

.cr6800.tfbel6800.obj,AP1.lfbel6800;=====================================================;;         Ring the Bell for the Motorola 6800         ;;                 by barrym 2013-03-31                ;;-----------------------------------------------------;; Rings the bell of an ascii terminal (console)       ;;   connected to a 1970s vintage SWTPC 6800 system,   ;;   which is the target device for this assembly.     ;; Many thanks to:                                     ;;   swtpc.com for hosting Michael Holley's documents! ;;   sbprojects.com for a very nice assembler!         ;;   swtpcemu.com for a very capable emulator!         ;; reg a holds the ascii char to be output             ;;-----------------------------------------------------;outeee=$e1d1;ROM: console putchar routine.or$0f00;-----------------------------------------------------;mainldaa#7;Load the ascii BEL charjsrouteee;  and print itswi;Return to the monitor.en

8086 Assembly

Using stdout

Translation of:X86 Assembly

This is how it'ssupposed to be done:

.modelsmall.stack1024.data.codestart:movah,02h;character outputmovdl,07h;bell codeint21h;call MS-DOSmovax,4C00h;exitint21h;return to MS-DOSendstart

But I couldn't hear anything on DOSBox when doing this.

The hard way

This version takes direct control over the PC's beeper to produce a tone wheneverBEL is passed toPrintChar.

.modelsmall.stack1024.data.codestart:moval,7callPrintCharmovax,4C00hint21h;return to DOS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;PrintChar:;Print AL to screenpushcxpushbxpushaxcmpal,7jneskipBELcallRingBelljmpdone_PrintCharskipBEL:movbl,15;text color will be whitemovah,0Ehint10h;prints ascii code stored in AL to the screen (this is a slightly different putc syscall)done_PrintChar:popaxpopbxpopcxret;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;RingBell:pushaxpushcxpushdx;if BEL is the argument passed to PrintChar, it will call this function and not actually print anything or advance the cursor;this uses the built-in beeper to simulate a beepmoval,10110110b;select counter 2, 16-bit modeout43h,almovax,0C00h;set pitch of beep - this is somewhat high but isn't too annoying. Feel free to adjust this valueout42h,almoval,ahout42h,almoval,3out61h,al;enable sound and timer modemovcx,0FFFFhmovdx,0Fh;set up loop countersbeepdelay:;delay lasts about half a secondloopbeepdelaymovcx,0FFFFhdecdxjnzbeepdelaymoval,0;muteout61h,al;cut the sound; mov bl,15; mov ax,0E20h                  ;print a spacebar to the terminal; int 10h                       ;uncomment these 3 lines if you want the BEL to "take up space" in the output streampopdxpopcxpopaxretendstart

Action!

PROC Wait(BYTE frames)  BYTE RTCLOK=$14  frames==+RTCLOK  WHILE frames#RTCLOK DO ODRETURNPROC Main()  BYTE    i,n=[3],    CH=$02FC ;Internal hardware value for last key pressed  PrintF("Press any key to hear %B bells...",n)  DO UNTIL CH#$FF OD  CH=$FF  FOR i=1 TO n  DO    Put(253) ;buzzer    Wait(20)  OD  Wait(100)RETURN
Output:

Screenshot from Atari 8-bit computer

Ada

withAda.Text_IO;useAda.Text_IO;withAda.Characters.Latin_1;procedureBellisbeginPut(Ada.Characters.Latin_1.BEL);endBell;

Applescript

beep

Arturo

print"\a"

Asymptote

beep()

Seebeep() in the Asymptote manual.

AutoHotkey

fileappend,`a,*

This requires that you compile the exe in console mode (see Lexikos script to change this) or pipe the file through more: autohotkey bell.ahk |more

AWK

BEGIN{print"\a"# Ring the bell}

BASIC

Applesoft BASIC

 10  PRINT  CHR$ (7);

Atari BASIC

PRINTCHR$(253)

Integer BASIC

You can't see it, but the bell character (Control G) is embedded in what looks like an empty string on line 10.

  10 PRINT "";: REM ^G IN QUOTES  20 END

IS-BASIC

PING

Locomotive Basic

10PRINTCHR$(7)

ZX Spectrum Basic

The ZX Spectrum had a speaker, rather than a bell. Here we use middle C as a bell tone, but we could produce a different note by changing the final zero to a different value.

BEEP0.2,0

Batch File

Source:Here

@echo offfor/f%%.in('forfiles /m "%~nx0" /c "cmd /c echo 0x07"')dosetbell=%%.echo%bell%

BBC BASIC

Assuming that the platform the program is running on rings the bell when CHR$7 is sent to the VDU driver:

VDU7

bc

print"\a"

beeswax

_7}

Befunge

7,@

Binary Lambda Calculus

The 2-byte BLC program20 07 in hex outputs ASCII code 7.

Bracmat

Run Bracmat in interactive mode (start Bracmat without command line arguments) and enter the following after the Bracmat prompt{?}:

\a

Alternatively, run Bracmat non-interactively. In DOS, you write

bracmat "put$\a"

In Linux, you do

bracmat 'put$\a'

Brainf***

Assuming the output stream is connected to a TTY, printing BEL should ring its bell.

  I+++++++-+-+.

C

#include<stdio.h>intmain(){printf("\a");return0;}

C#

Inside a function:

// the simple version:System.Console.Write("\a");// will beepSystem.Threading.Thread.Sleep(1000);// will wait for 1 secondSystem.Console.Beep();// will beep a second timeSystem.Threading.Thread.Sleep(1000);// System.Console.Beep() also accepts (int)hertz and (int)duration in milliseconds:System.Console.Beep(440,2000);// default "concert pitch" for 2 seconds

C++

#include<iostream>intmain(){std::cout<<"\a";return0;}

Clojure

(println(char7))

COBOL

Using the standard screen section:

Works with:X/Open COBOL
Works with:COBOL 2002
IDENTIFICATIONDIVISION.PROGRAM-ID.ring-terminal-bell.DATADIVISION.SCREENSECTION.01ringerBELL.PROCEDUREDIVISION.DISPLAYringer.STOPRUN.ENDPROGRAMring-terminal-bell.

Using the ASCII code directly:

Works with:COBOL-85
      *> Tectonics: cobc -xj ring-terminal-bell.cob --std=cobol85IDENTIFICATIONDIVISION.PROGRAM-ID.ring-ascii-bell.ENVIRONMENTDIVISION.CONFIGURATIONSECTION.OBJECT-COMPUTER.PROGRAMCOLLATINGSEQUENCEISASCII.SPECIAL-NAMES.ALPHABETASCIIISSTANDARD-1.PROCEDUREDIVISION.DISPLAYFUNCTIONCHAR(8)WITHNOADVANCING.      *>   COBOL indexes starting from 1.STOPRUN.ENDPROGRAMring-ascii-bell.
Works with:Visual COBOL
IDENTIFICATIONDIVISION.PROGRAM-ID.mf-bell.DATADIVISION.WORKING-STORAGESECTION.01bell-codePIC XUSAGECOMP-XVALUE22.01dummy-paramPIC X.PROCEDUREDIVISION.CALLX"AF"USINGbell-code,dummy-paramGOBACK.ENDPROGRAMmf-bell.

Common Lisp

(formatt"~C"(code-char7))

D

voidmain(){importstd.stdio;writeln('\a');}

dc

7P

Delphi

programTerminalBell;{$APPTYPE CONSOLE}beginWriteln(#7);end.

E

print("\u0007")

Emacs Lisp

(ding);; ring the bell(beep);; the same thing

On a tty or in-batch mode this emits a BEL character. In a GUI it does whatever suits the window system. Variablesvisible-bell andring-bell-function can control the behaviour.

beep was originally calledfeep, but that changed, recently :-)

Fri Dec 13 00:52:16 1985  Richard M. Stallman  (rms at prep)* subr.el: Rename feep to beep, a more traditional name.

F#

openSystemConsole.Beep()

Factor

USE:io"\u{7}"print

Or:

USING:iostrings;71stringprint

Forth

7emit
Works with:GNU Forth
#bellemit
Works with:iForth
^Gemit

FreeBASIC

' FB 1.05.0 Win64Print!"\a"Sleep

FutureBasic

beephandleevents

gnuplot

print"\007"

Go

packagemainimport"fmt"funcmain(){fmt.Print("\a")}

Groovy

println'\7'

Haskell

main=putStr"\a"

Icon andUnicon

Works on both Icon and Unicon.

proceduremain()write("\7")# ASCII 7 rings the bell under Bashend

J

This j sentence reads "Seven from alphabet."

7{a.NB. noun a. is a complete ASCII ordered character vector.

Java

publicclassBell{publicstaticvoidmain(String[]args){java.awt.Toolkit.getDefaultToolkit().beep();//orSystem.out.println((char)7);}}

Joy

7 putch.

Julia

Works with:Linux
println("This should ring a bell.\a")
Output:
This should ring a bell.

And it does, provided that the bell is enabled on your terminal.

Kotlin

Works with:Windows version 10
// version 1.1.2funmain(args:Array<String>){println("\u0007")}

Lang

fn.println(fn.toChar(7))

Lasso

stdoutnl('\a')

Logo

type char 7

Lua

print("\a")

M2000 Interpreter

M2000 Environment has own console (not the one provided from system). Console used for graphics, and has 32 layers for text or and graphics and as sprites too. We can alter the console by code, moving to any monitor, changing font, font size and, line space. Also there is a split function, where the lower part can scroll, and the upper part used as header (we can write/draw in the upper part also, but CLS - clear screen- statement clear only the lower part).

Using Windows Bell

Async beep. If another start while beeps (it is a bell), then stop

Module CheckIt {      After 300 {beep}      Print "Begin"      for i=0 to 100 {            wait 10            Print i      }      Print "End"}CheckIt


Play tone at 1khz or specific hz

Execution stop to play tone

Tone (1khz)Tone 200 (1 kgz 200 ms)Tone 200, 5000 (5khz. 200ms)
Module CheckIt {      After 300 {Tone 200}      Print "Begin"      for i=0 to 100 {            wait 10            Print i      }      Print "End"}CheckIt


Play melody with beeper

Execution stop to play tune

Tune melody$Tune duration_per_note, melody$
Module CheckIt {      After 300 {Tune 300, "C3BC#"}      Print "Begin"      for i=0 to 100 {            wait 10            Print i      }      Print "End"}CheckIt


using midi to send music scores

Play a score in each of 16 voices (async, programming internal midi, problem with async in Wine Linux). We can make a piano using keyboard and play/score commands.

Module CheckIt {      Score 1, 500, "c@2dc @2ef"      Play 1, 19  ' attach a music score to an organ      Print "Begin"      for i=0 to 100 {            wait 10            Print i      }      Print "End"      \\ stop play, remove this and music continue, in console prompt      Play 0}CheckIt

There are other statements like Sound, and Background filename$ to play background music.

Mathematica /Wolfram Language

Print["\007"]

MUMPS

write $char(7)

Nanoquery

print chr(7)

Nemerle

usingSystem.Console;moduleBeep{Main():void{Write("\a");System.Threading.Thread.Sleep(1000);Beep();System.Threading.Thread.Sleep(1000);Beep(2600,1000);// limited OS support}}

NetRexx

/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsbinaryrunSample(arg)return--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~methodrunSample(arg)privatestaticdoBEL=8x07jtk=java.awt.toolkit.getDefaultToolkit()say'Bing!'(RexxBEL).d2cThread.sleep(500)say'Ding\x07-ding\u0007!'Thread.sleep(500)say'Beep!'jtk.beep()catchex=Exceptionex.printStackTrace()endreturn

Nim

echo"\a"

Nu

Works with:Nushell version 0.96.1
char bel

or

print "\a"

Objeck

7->As(Char)->PrintLine();

OCaml

let()=print_string"\x07"

PARI/GP

Works with:PARI/GP version 2.7.4 and above
\\ Ringing the terminal bell.\\ 8/14/2016 aevStrchr(7) \\ press <Enter>
or
print(Strchr(7)); \\ press <Enter>
Output:
(11:12) gp > Strchr(7) \\ press <Enter>%6 = ""(11:13) gp > print(Strchr(7)); \\ press <Enter>(11:14) gp >

Pascal

See Delphi

PascalABC.NET

##Console.Beep(440,1000);

Perl

print"\a";

Phix

puts(1,"\x07")

Ineffective under pwa/p2js - just displays an unknown character glyph.

PHP

<?phpecho"\007";

PicoLisp

(beep)

PL/I

   declare bell character (1);   unspec (bell) = '00000111'b;   put edit (bell) (a);

PostScript

The following will only work in a PostScript interpreter that sends output to a terminal. It will very likely not make a printer beep.

(\007)print

PowerShell

One can either use the ASCIIBEL character which only works in a console (i.e. not in a graphical PowerShell host such as PowerShell ISE):

"`a"

or use the .NETConsole class which works independent of the host application:

[Console]::Beep()

PureBasic

Print(#BEL$)

Python

In Python 2.7.x:

print"\a"

In Python 3.x:

print("\a")

Quackery

On some platforms the bell will not ring until the output buffer is flushed e.g. by a cr/lf.

ding

R

alarm()

Racket

#langracket(require(planetneil/charterm:3:0))(with-charterm(void(charterm-bell)))

Raku

(formerly Perl 6)

print7.chr;

Retro

7 putc

REXX

There is no standard REXX built-in function to handle the sounding of the bell or a PC's speaker.

However, some REXX interpreters have added a non-standard BIF.

/*REXX program illustrates methods to  ring the terminal bell  or  use the PC speaker.  *//*╔═══════════════════════════════════════════════════════════════╗                       ║                                                               ║                       ║  Note that the  hexadecimal code  to ring the  terminal bell  ║                       ║  is different on an ASCII machine than an EBCDIC machine.     ║                       ║                                                               ║                       ║  On an  ASCII machine,  it is  (hexadecimal)  '07'x.          ║                       ║   "  " EBCDIC    "       "  "        "        '2F'x.          ║                       ║                                                               ║                       ╚═══════════════════════════════════════════════════════════════╝*/if3=='F3'thenbell='2f'x/*we are running on an EBCDIC machine. */elsebell='07'x/* "  "     "     "  "  ASCII    "     */saybell/*sound the  bell  on the terminal.    */saycopies(bell,20)/*as above,  but much more annoying.   *//*╔═══════════════════════════════════════════════════════════════╗                       ║                                                               ║                       ║  Some REXX interpreters have a  built-in function  (BIF)  to  ║                       ║  to produce a sound on the PC speaker, the sound is specified ║                       ║  by frequency  and  an optional  duration.                    ║                       ║                                                               ║                       ╚═══════════════════════════════════════════════════════════════╝*//* [↓]  supported by Regina REXX:              */freq=1200/*frequency in  (nearest)  cycles per second.  */callbeepfreq/*sounds the PC speaker, duration=  1   second.*/ms=500/*duration in milliseconds.                    */callbeepfreq,ms/*  "     "   "    "         "     1/2     "   *//* [↓]  supported by PC/REXX  &  Personal REXX:*/freq=2000/*frequency in  (nearest)  cycles per second.  */callsoundfreq/*sounds PC speaker, duration=   .2   second.  */secs=.333/*duration in seconds (round to nearest tenth).*/callsoundfreq,secs/*  "     "    "         "      3/10     "     *//*stick a fork in it, we're done making noises.*/

Ring

see char(7)

Ruby

print"\a"

Rust

fnmain(){print!("\x07");}

Scala

java.awt.Toolkit.getDefaultToolkit().beep()

Seed7

$ include "seed7_05.s7i";const proc: main is func  begin    write("\a");  end func;

Sidef

print"\a";

SNUSP

$+++++++.#

Standard ML

val()=print"\a"

Tcl

puts-nonewline"\a";flushstdout

UNIX Shell

Works with:Bourne Shell
Works with:bash
#!/bin/sh# Ring the terminal bell# echo "\a" # does not work in some shellstputbel

Wren

System.print("\a")

X86 Assembly

;Assemble with: tasm; tlink /t        .model  tiny        .code        org     100h            ;.com files start herestart:  mov     ah, 02h         ;character output        mov     dl, 07h         ;bell code        int     21h             ;call MS-DOS        ret                     ;return to MS-DOS        end     start

XPL0

code ChOut=8;ChOut(0,7)

zkl

print("\x07");
Retrieved from "https://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell?oldid=376341"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2025 Movatter.jp