Play recorded sounds: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(6 intermediate revisions by 3 users not shown)
Line 143:
END</syntaxhighlight>
 
=={{header|C}}==
==={{libheader|Gadget}}===
<p>The functions written below access the operating system, running "aplay" (Linux Debian 11 and derivatives).
They work very well, and you can see an example of them working in a terminal game called "Pacman.c", which can be found at the following path:</p>
 
https://github.com/DanielStuardo/Gadget
 
<syntaxhighlight lang="c">
/*
plays the sound file, and returns a string with the PID number of that play.
 
Call:
char* pid_sound = put_sound( "file.wav" );
or
String pid_sound;
....
Fn_let( pid_sound, put_sound( "file.wav" ) );
*/
char * put_sound( char* file_sound )
{
String PID_SOUND;
system( file_sound );
PID_SOUND = `pidof aplay`;
char ot = Set_new_sep(' ');
Fn_let( PID_SOUND, Get_token(PID_SOUND, 1));
Set_token_sep(ot);
return PID_SOUND;
}
 
/*
Deletes a sound that is playing.
It may happen that when trying to kill the process, "aplay" has already finished.
Call:
kill_sound( pid_sound );
Free secure pid_sound;
*/
void kill_sound( char * PID_SOUND )
{
String pid;
pid = `pidof aplay`;
if( Occurs( PID_SOUND, pid ){
char strkill[256];
sprintf( strkill, "kill -9 %s </dev/null >/dev/null 2>&1 &", PID_SOUND);
system(strkill);
}
Free secure pid;
}
 
/*
Clears all sounds that are playing.
Call:
kill_all_sounds();
and then free all string of pid's:
Free secure pid1, pid2, ... ;
*/
void kill_all_sounds()
{
String PID;
Fn_let ( PID, Get_sys("pidof aplay" ));
if (strlen(PID)>0){
char cpids[256];
sprintf(cpids,"kill -9 %s </dev/null >/dev/null 2>&1",PID);
system(cpids);
}
Free secure PID;
}
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 181 ⟶ 250:
sndPlaySound('SoundFile.wav', SND_NODEFAULT OR SND_ASYNC);
end.</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
'''Library: AVFoundation'''
 
FB has several native ways to play recorded sounds, ranging from simple to commercial. It also can play a variety of audio formats including mp3, m4a, aiff, wav, etc. This task code uses the AVFoundation library to create a basic player with simple controls including a popup menu from which bundled audio files can be selected.
<syntaxhighlight lang="futurebasic">
include "Tlbx AVFoundation.incl"
 
include resources "Here Comes the Sun.mp3"
include resources "Wake Me Up.mp3"
include resources "I Walk the Line.aif"
 
_window = 1
begin enum 1
_progInd
_timeLabel
_durLabel
_playBtn
_pauseBtn
_stopBtn
_selectBtn
end enum
 
void local fn FixButtons
dispatchmain // configure UI elements on main thread
AVAudioPlayerRef player = fn AppProperty( @"Player" )
if ( player )
button _playBtn, NO
if ( fn AVAudioPlayerIsPlaying( player ) )
button _pauseBtn, YES,, @"Pause"
button _stopBtn, YES
else
button _pauseBtn, YES,, @"Resume"
end if
else
textlabel _timeLabel, @"--.-"
progressindicator _progInd, 0.0
textlabel _durLabel, @"--.-"
button _playBtn, YES
button _pauseBtn, NO,, @"Pause"
button _stopBtn, NO
end if
dispatchend
end fn
 
void local fn BuildWindow
window _window, @"AVAudioPlayer", (0,0,480,87), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
textlabel _timeLabel, @"--.-", (18,52,38,16)
ControlSetAlignment( _timeLabel, NSTextAlignmentRight )
progressindicator _progInd,, (62,48,356,20)
ProgressIndicatorSetUsesThreadedAnimation( _progInd, NO )
textlabel _durLabel, @"--.-", (424,52,38,16)
button _playBtn,,, @"Start", (14,13,89,32)
button _pauseBtn, NO,, @"Pause", (103,13,89,32)
button _stopBtn, NO,, @"Stop", (192,13,89,32)
popupbutton _selectBtn,,, @"Here Comes the Sun;Wake Me Up;I Walk the Line", (290,17,170,25)
end fn
 
void local fn Cleanup
fn FixButtons
AppRemoveProperty( @"Player" )
AppRemoveProperty( @"Timer" )
end fn
 
void local fn DidFinishPlayingHandler( player as AVAudioPlayerRef, success as BOOL, userData as ptr )
fn Cleanup
end fn
 
local fn MyAppTimer( timer as CFRunLoopTimerRef )
dispatchmain // configure UI elements on main thread
CFTimeInterval ti, dur
AVAudioPlayerRef player = fn AppProperty( @"Player" )
if ( player )
ti = fn AVAudioPlayerCurrentTime( player )
dur = fn AVAudioPlayerDuration( player )
ProgressIndicatorSetDoubleValue( _progInd, ti*100/dur )
textlabel _timeLabel, fn StringWithFormat( @"%.1f", ti )
end if
dispatchend
end fn
 
void local fn PlayAction
CFURLRef url = fn AppProperty( @"songURL" )
AVAudioPlayerRef player = fn AVAudioPlayerWithContentsOfURL( url, NULL )
AVAudioPlayerSetDidFinishPlayingHandler( player, @fn DidFinishPlayingHandler, NULL )
AppSetProperty( @"Player", player )
textlabel _durLabel, fn StringWithFormat(@"%.1f",fn AVAudioPlayerDuration(player))
CFRunLoopTimerRef t = fn AppSetTimer( 0.1, @fn MyAppTimer, YES )
AppSetProperty( @"Timer", t )
fn AVAudioPlayerPlay( player )
fn FixButtons
end fn
 
void local fn PauseAction
AVAudioPlayerRef player = fn AppProperty( @"Player" )
if ( player )
if ( fn AVAudioPlayerIsPlaying( player ) )
AVAudioPlayerPause( player )
else
fn AVAudioPlayerPlay( player )
end if
end if
fn FixButtons
end fn
 
void local fn StopAction
AVAudioPlayerRef player = fn AppProperty( @"Player" )
if ( player )
AVAudioPlayerStop( player )
end if
fn Cleanup
end fn
 
 
void local fn SongURL( songTitle as CFStringRef )
CFURLRef url
select (songTitle)
case @"Here Comes the Sun" : url = fn BundleURLForResource( fn BundleMain, songTitle, @"mp3", NULL )
case @"Wake Me Up" : url = fn BundleURLForResource( fn BundleMain, songTitle, @"mp3", NULL )
case @"I Walk the Line" : url = fn BundleURLForResource( fn BundleMain, songTitle, @"aif", NULL )
end select
AppSetProperty( @"songURL", url )
end fn
 
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _playBtn : fn StopAction : fn SongURL( fn PopUpButtonTitleOfSelectedItem( _selectBtn ) ) : fn PlayAction
case _pauseBtn : fn PauseAction
case _stopBtn : fn StopAction
case _selectBtn : fn StopAction : fn SongURL( fn PopUpButtonTitleOfSelectedItem( _selectBtn ) ) : fn PlayAction
end select
case _windowWillClose : end
end select
end fn
 
fn BuildWindow
 
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:AVAudio Player.png]]
 
 
 
 
=={{header|Go}}==
Line 264 ⟶ 484:
</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
 
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
 
public final class PlayRecordedSounds {
 
public static void main(String[] aArgs) {
PlayRecordedSounds soundPlayer = new PlayRecordedSounds();
soundPlayer.play();
scanner = new Scanner(System.in);
int choice = 0;
while ( choice != 6 ) {
System.out.println("1. Pause");
System.out.println("2. Resume");
System.out.println("3. Restart");
System.out.println("4. Jump to specific time");
System.out.println("5. Stop");
System.out.println("6. Quit the program");
choice = scanner.nextInt();
soundPlayer.select(choice);
}
scanner.close();
}
private enum Status { PLAYING, PAUSED, STOPPED }
 
private PlayRecordedSounds() {
resetAudioStream();
}
private void select(int aChoice) {
switch ( aChoice ) {
case 1 -> pause();
case 2 -> resume();
case 3 -> restart();
case 4 -> jump();
case 5 -> stop();
case 6 -> quit();
default -> { /* Take no action */ }
}
}
private void play() {
status = Status.PLAYING;
clip.start();
}
private void pause() {
if ( status == Status.PAUSED ) {
System.out.println("The audio is already paused");
return;
}
currentClipPosition = clip.getMicrosecondPosition();
clip.stop();
status = Status.PAUSED;
}
private void resume() {
if ( status == Status.PLAYING ) {
System.out.println("The audio is already being played");
return;
}
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentClipPosition);
status = Status.PLAYING;
play();
}
private void restart() {
clip.stop();
clip.close();
resetAudioStream();
currentClipPosition = 0;
clip.setMicrosecondPosition(currentClipPosition);
status = Status.PLAYING;
play();
}
private void jump() {
System.out.println("Select a time between 0 and " + clip.getMicrosecondLength());
final long request = scanner.nextLong();
if ( request > 0 && request < clip.getMicrosecondLength() ) {
clip.stop();
clip.close();
resetAudioStream();
currentClipPosition = request;
clip.setMicrosecondPosition(currentClipPosition);
status = Status.PLAYING;
play();
}
}
private void stop() {
currentClipPosition = 0;
clip.stop();
clip.close();
status = Status.STOPPED;
}
private void quit() {
try {
scanner.close();
clip.close();
audioStream.close();
Runtime.getRuntime().exit(0);
} catch (IOException ioe) {
ioe.printStackTrace(System.err);
}
}
private void resetAudioStream() {
try {
audioStream = AudioSystem.getAudioInputStream( new File(FILE_PATH) );
clip = AudioSystem.getClip();
clip.open(audioStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException exception) {
exception.printStackTrace(System.err);
}
}
 
private static Scanner scanner;
private static Clip clip;
private static long currentClipPosition;
private static Status status;
private static AudioInputStream audioStream;
private static final String FILE_PATH = "./test_piece.wav";
}
</syntaxhighlight>
 
=={{header|Julia}}==
Line 934 ⟶ 1,299:
 
It is certainly suitable for game sound effects (it's a game engine) and can play music at CD quality as well.
<syntaxhighlight lang="ecmascriptwren">import "audio" for AudioEngine
import "dome" for Process
 
9,488

edits