AndreMiras / pycaw

Python Core Audio Windows Library
MIT License
385 stars 67 forks source link

Is there any way to use IAudioEndPointVolume interface with AudioSession instances? I want to read the app volume (any process volume) is playing now or not or current value of comig sound? #78

Closed MusaAkyuz closed 1 year ago

MusaAkyuz commented 1 year ago

Make sure to give enough information to help debugging your issue. Here are some hints:

MusaAkyuz commented 1 year ago
from pycaw.pycaw import AudioUtilities

def is_sound_playing():
    devices = AudioUtilities.GetAllDevices()
    volume_interface = devices[0].Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
    volume = cast(volume_interface, POINTER(IAudioEndpointVolume))

    # Check the audio level for a few seconds
    duration = 5  # Duration to monitor sound in seconds
    interval = 0.1  # Interval between audio level checks
    start_time = time.time()

    while time.time() - start_time < duration:
        audio_level = volume.GetMasterVolumeLevelScalar()

        if audio_level > 0.01:  # Adjust this threshold according to your needs
            return True

        time.sleep(interval)

    return False

I mean, when using GetAllDevices(), is_sound_playing() is working to read that the sound is coming or not? But sessions can't do that.

MusaAkyuz commented 1 year ago

Oh ı solved it. Sorry for alert. :) I used AudioSessionState to read state is active.

from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
from pycaw.constants import AudioSessionState

sessions = AudioUtilities.GetAllSessions()
# Find the target application by its name
edge_app_name = "msedge.exe"
spotify_app_name = "Spotify.exe"

#edge_session = AudioUtilities.GetSession(edge_app_name)
#spotify_session = AudioUtilities.GetSession(spotify_app_name)

while True:
    for session in sessions:
        if session.Process and session.Process.name() == edge_app_name:
            edge_volume = session._ctl.QueryInterface(ISimpleAudioVolume)
            is_sound = session.State == AudioSessionState.Active
            current_volume = edge_volume.GetMasterVolume()
            print("Current volume:", current_volume)
            print("is_sound: ", is_sound)
AndreMiras commented 1 year ago

Thank you for coming back with the solution that could always be helpful to others :pray: