AudioSink#
This example demonstrates how to use the AudioSink
class.
import rpaudio
import time
kill_audio = False
AUDIO_FILE = r"C:\Users\16145\Desktop\a1.mp3"
def on_audio_stop():
global kill_audio
kill_audio = True
print("Audio has stopped")
def play_audio():
# Initialize and load the audio file
handler = rpaudio.AudioSink(callback=on_audio_stop).load_audio(AUDIO_FILE)
# Set the volume to 50% (optional)
handler.set_volume(0.5)
handler.play()
# Loop until the audio completes, print the time elapsed
i = 0
while not kill_audio:
i += 1
time.sleep(1)
print(i)
if __name__ == "__main__":
play_audio()
import rpaudio
import asyncio
AUDIO_FILE = r"C:\Users\16145\Desktop\exc.mp3"
def on_audio_stop():
print("Audio has stopped")
async def play_audio():
handler = rpaudio.AudioSink(
callback=on_audio_stop).load_audio(AUDIO_FILE)
print(handler.metadata_dict)
handler.set_volume(0.5)
handler.play()
count = 0
while True:
await asyncio.sleep(1)
count += 1
handler.cancel_callback()
if count == 4:
# Pause the audio for 2 seconds
print("Pausing audio")
handler.set_volume(0.2)
print(handler.get_volume())
handler.pause()
await asyncio.sleep(1)
print(handler.is_playing)
if count == 5:
# turn down the volume
print("Resuming audio, raise volume")
handler.set_volume(0.5)
handler.play()
if count == 7:
# Seek to 10 seconds
print(f"Current position: {handler.get_pos()}")
handler.try_seek(10)
await asyncio.sleep(1)
print(f"Position after seek: {handler.get_pos()}")
if count == 10:
# Stop the audio
print(handler.get_volume())
handler.stop()
async def sleep_loop():
for i in range(20):
print(f"Sleeping {i}")
await asyncio.sleep(1)
async def main():
await asyncio.gather(play_audio(), sleep_loop())
asyncio.run(main())
import rpaudio
import asyncio
from rpaudio.effects import FadeIn, FadeOut, ChangeSpeed
kill_audio = False
AUDIO_FILE = r"C:\Users\16145\Desktop\exc.mp3"
def on_audio_stop():
global kill_audio
kill_audio = True
print("Audio has stopped")
async def play_audio():
handler = rpaudio.AudioSink(callback=on_audio_stop).load_audio(AUDIO_FILE)
print(handler.metadata_dict)
await asyncio.sleep(0.3)
handler.set_volume(0.0)
fade_in_effect = FadeIn(duration=10.0, apply_after=0.0)
fade_out_effect = FadeOut(duration=10.0, apply_after=10.0)
speed_up = ChangeSpeed(apply_after=5.0, end_val=1.5, duration=3.0)
effects_list = [fade_in_effect, fade_out_effect, speed_up]
handler.apply_effects(effects_list)
handler.play()
i = 0
while not kill_audio:
i += 1
await asyncio.sleep(1)
print(i)
if i == 15:
handler.stop()
async def sleep_loop():
global kill_audio
i = 0
while not kill_audio:
await asyncio.sleep(1)
i += 1
async def main():
await asyncio.gather(play_audio(), sleep_loop())
asyncio.run(main())