You can do this natively with PowerShell. PowerShell is included with Windows Vista and later, and can be downloaded from Microsoft for older versions.
Wave files
PowerShell can be used to load the System.Media.SoundPlayer
.NET class, which can be used to play a wave file.
(New-Object Media.SoundPlayer "C:\WINDOWS\Media\notify.wav").Play();
If you want, you can run this from the normal command line:
powershell -c (New-Object Media.SoundPlayer "C:\Windows\Media\notify.wav").PlaySync();
(note that PlaySync
is used in the second example since the standard asynchronous play would be interrupted by the PowerShell process closing when launched like this)
And if you wanted to play only the first, say, 5 seconds of the sound:
powershell -c (New-Object Media.SoundPlayer "C:\Windows\Media\notify.wav").Play(); Start-Sleep -s 5; Exit;
Beep
A beep can be easily accomplished in the normal command line with echo ^G
(where ^G
represents BEL, ASCII character 7, inserted with Ctrl + G), as described in other answers. In the interest of completeness, here’s the PowerShell method:
echo ^G
Yes, it’s the same as the cmd
one. echo
in PowerShell is an alias (i.e. means the same thing) to Write-Host
, which displays something to the screen (or triggers the Windows notification sound in the case of BEL
).
An alternative method in PowerShell is to use the escape sequence for BEL, rather than inserting a literal BEL character with Ctrl + G:
echo `a
`
is PowerShell’s escape character, which modifies the meaning of the character after it. An escaped a
indicates BEL. The advantage of this approach is it is easier and more visible when typed into a script.
To run this in a batch file (again, Vista or later):
powershell -c echo `a
source
-
1
Open up Command Prompt on your computer.(Go to a windows computer and in «RUN» type in command prompt.
-
2
Then a black screen will pop up. In that type in CTRL+G, then it will make a a «^G», however many times you press it is how many times it will BEEP.
Advertisement
-
3
Press enter and have fun!
-
4
You’re finished!
-
5
To make this into a batch file command:
-
6
Type copy con beep.txt [return]
-
7
[ctrl-G][ctrl-Z][return]
-
8
The system should say ‘file copied’.
-
9
To play the beep, type the command line:
-
10
Type beep.txt
-
11
To make two beeps, type:
-
12
Type beep.txt beep.txt
-
13
If you type in beep.txt, the editor should open the beep.txt file. It will have a single black dot in it. Select the dot, copy it and paste it as many times as you want. Each copied dot is a beep. Save the file and presto, multiple system beeps. Have fun.
Advertisement
Add New Question
-
Question
I did this, but it only opens the text file — no audible beep. Any ideas why?
It’s not a batch file. Make it into beep.bat instead of beep.txt.
-
Question
Does this require a sound card?
No.
-
Question
This doesn’t work in Win 8.1 command prompt: «Not recongized as an internal or extrenal command». Syntax for 8.1?
Create a batch file and type inside it: «echo ^G» where ^G is the character representing the beep as mentioned in this page. If it makes double beeps, add «echo off» line at the beginning of the batch file.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
-
Command prompt can screw up your whole computer if you do something wrong.
-
When in command prompt, do NOT type in anything else, but what has been instructed, unless you know what you are doing.
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 191,275 times.
Did this article help you?
WARNING: rundll32.exe Kernel32.dll,Beep 750,300
no longer works well from the command line on modern windows systems as rundll32 no longer accepts integer values (again, through the command line) and this will play the beep with the default values which is too long (and frequency is irritating):
REM Again, with warnings about running this from the command line...
rundll32.exe Kernel32.dll,Beep 750,300
or
rundll32.exe cmdext.dll,MessageBeepStub
or
rundll32 user32.dll,MessageBeep
With rundll functions you won’t need special symbols like ^G
. With the first method you can also set the frequency and the time you want to beep, though see the warning that those parameters no longer work on modern systems from the command line and will instead play the annoying defaults.
UPDATE
Other options are calling Console.Beep
from .NET using PowerShell:
powershell "[console]::beep(500,300)"
or using systemSounds.bat
call systemsounds.bat beep
The capability of beeping depends on the mainboard and if the mainboard has a system speaker — which has increasingly become a rarity as systems tend to depend solely on «normal» speakers instead. An alternative is to play sound through those speakers. Here are some options:
Using the speaking capabilities of the SAPI.SpVoice
:
mshta "javascript:code(close((V=(v=new ActiveXObject('SAPI.SpVoice')).GetVoices()).count&&v.Speak('beep')))"
Here this is wrapped in a batch file and the words can be passed as an argument.
SAPI.SpVoice
can be used for playing WAV files and you have some packaged with the default Windows installation. You can use this script:
spplayer.bat "C:\Windows\Media\Windows Navigation Start.wav"
Another option: Using the windows media player active-x objects to play a sound. On Windows XP it was not installed by default, but I think for the newer Windows versions it is. It also can play MP3 files:
call mediarunner.bat "C:\Windows\Media\Ring03.wav"
And one that is a little bit obscure — using the <bgsound>
tag from internet explorer (which also can play mp3 files). Here’s the script:
call soundplayer.bat "C:\Windows\Media\tada.wav"
And here’s a way to use the BEL character to produce sound with easy to copy-paste code (I’ve called it a beeper.bat
):
@echo off
setlocal
::Define a Linefeed variable
(set LF=^
%=-=%
)
for /f eol^=^%LF%%LF%^ delims^= %%A in (
'forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x07"'
) do echo(%%A
Время на прочтение
2 мин
Количество просмотров 3.1K
Мне приходится часто запускать довольно долгие операции из командной строки. Например Maven build или тесты. Естественно на «Матрицу» любоваться быстро надоедает, и переключаешься на какие-то другие задачи. Однако хочется чтобы тебе сразу сообщили что можно работать дальше. По умолчанию консоль Windows не предоставляет возможности назначить звуковой сигнал на завершение операции. Но ответ прост.
Можно всего-лишь добавить к команде небольшое дополнение.
Например в батнике который вызывает бильд, можно написать так:
call mvn process-resources war:exploded & c:\programms\MPlayer\mplayer.exe "d:\programms\res\ok.wav" > nul
Теперь после выполнения mvn — запустится mplayer и проиграет ok.wav, причем лишнего мусора в консоль не добавит(изза «> nul» ). Естественно можно воспользоваться любым другом плеером, или просто вызвать «ok.wav», тогда запустится проигрыватель по умолчанию, но мплеер мне нравится тем, что без гуя.
Для удобства можно можно вызов звуков вынести в отдельные баты, и положить где-нибудь, где прописан path, тогда их можно вызывать и для других команд. Можно сделать два батника для успешного завершения и для ошибки соответственно.
Итак:
build.bat
call mvn process-resources war:exploded && success.bat || fail.bat
success.bat:
@c:\programms\MPlayer\mplayer.exe "d:\programms\res\sucess.wav" > nul
fail.bat:
@c:\programms\MPlayer\mplayer.exe "d:\programms\res\error.wav" > nul
Запустив build можно больше не переключатся в консоль, мы и так узнаем когда процесс закончится, и успешно или нет.
Ну и в конце делаем !.bat с таким содержимым:
@%* && success.bat || fail.bat
Теперь можно запустить любую команду:
! copy очень_большой.файл, и услышать результат.
Звуки можно взять стандартные из Windows, или любые другие. Мне нравятся эти TSCUpd00.wav, TSCErr01.wav.
Windows XP Redirection
На роль открыватель Америки не претендую, если кто-то знает более простой способ — поделитесь.
Вы можете сделать это изначально с PowerShell. PowerShell входит в состав Windows Vista и более поздних версий и может быть загружен с веб-сайта Microsoft для более старых версий.
Волновые файлы
PowerShell можно использовать для загрузки System.Media.SoundPlayer
Класс.NET, который можно использовать для воспроизведения волнового файла.
(New-Object Media.SoundPlayer "C:\WINDOWS\Media\notify.wav").Play();
Если вы хотите, вы можете запустить это из обычной командной строки:
powershell -c (New-Object Media.SoundPlayer "C:\Windows\Media\notify.wav").PlaySync();
(Обратите внимание, что PlaySync
используется во втором примере, так как стандартное асинхронное воспроизведение будет прервано закрытием процесса PowerShell при его запуске следующим образом)
И если вы хотите воспроизвести только первые, скажем, 5 секунд звука:
powershell -c (New-Object Media.SoundPlayer "C:\Windows\Media\notify.wav").Play(); Start-Sleep -s 5; Exit;
гудок
Звуковой сигнал может быть легко выполнен в обычной командной строке с echo ^G
(где ^G
представляет BEL, символ ASCII 7, вставленный с помощью Ctrl + G), как описано в других ответах. В целях полноты, вот метод PowerShell:
echo ^G
Да, это так же, как cmd
один. echo
в PowerShell это псевдоним (то есть означает то же самое) Write-Host
, который отображает что-то на экране (или вызывает звук уведомления Windows в случае BEL
).
Альтернативный метод в PowerShell — использовать escape-последовательность для BEL, а не вставлять буквенный символ BEL с помощью Ctrl + G:
echo `a
`
является escape-символом PowerShell, который изменяет значение символа после него. Сбежавший a
указывает на бел. Преимущество этого подхода в том, что он легче и более заметен при вводе в скрипт.
Чтобы запустить это в командном файле (снова, Vista или позже):
powershell -c echo `a
источник