0

I'm trying to build a music player using pygame, but I'm facing a lot of problems.
The basic idea is to put some songs in a list and access them.

  1. For shuffle option, I have imported random module and used randint method to generate random numbers which will be used as index values to access the list while the loop is true. The numbers are being generated as expected but mixer.music.load(song_list[random_numbers) is not working and no songs are playing.

  2. For the looping option, I have used a while loop that plays a particular song a certain number of times. I have written a code that is supposed to ask the user whether to continue listening or not when the loop breaks. Instead, this piece of code is being implemented before the loop breaks.

  3. I have used if statements to implement shuffle and loop options. If both are false, the else statement will be executed and the songs are supposed to play in sequential order. For this, I have used a 'for' loop to iterate over the song list, but 'for' loop is not working the loop breaks without even being executed

# playlist using python
def dir_path(path):
    try:
        import os
        import time
        import random
        from pygame import mixer
        mixer.init()
        # songs list
        songs_list = []
        lis = os.listdir(path)
        for i in lis:
            a = os.path.join(path, i)
            songs_list.append(a)

        # to enable shuffling
        shuffle = input('enable shuffling? y/n: ')
        if shuffle.lower() == 'y':
            b = []
            t_end = time.time() + 60 * float(input('play time in minutes: '))
            while time.time() < t_end:
                a = random.randint(0, len(songs_list) - 1)
                if a not in b:
                    b.append(a)
                    mixer.music.load(songs_list[a])
                    mixer.music.play()
                if len(b) == len(songs_list):
                    b.clear()
            print('thanks for listening :)')

        # to enable looping
        elif shuffle.lower() == 'n':
            loop = input('enable looping? y/n: ')
            if loop.lower() == 'y':
                sl_num = 1
                for i in lis:
                    print(f'{sl_num}) {i}')
                    sl_num += 1
                sl_no = int(input('sl_no of the song: '))
                loop_no = int(input('number of loops: '))
                loop_times = 0
                while loop_times < loop_no:
                    if sl_no <= len(songs_list):
                        mixer.music.load(songs_list[sl_no - 1])
                        mixer.music.play()
                        loop_times += 1
                    else:
                        print(f'only {len(songs_list)} songs are available')
                        loop_times = loop_no
                    if loop_times == loop_no:
                        conn = input('continue listening? y/n: ')
                        if conn.lower() == 'y':
                            dir_path(path)
                        elif conn.lower() == 'n':
                            print('Thanks for listening :)')
                            break
                        else:
                            print('invalid command')
                            break

            # to play songs in order
            elif loop.lower() == 'n':
                for i in range(0, len(songs_list)):
                    mixer.music.load(songs_list[i])
                    mixer.music.play()
                print('thanks for listening :)')

            else:
                print('invalid command')
        else:
            print('invalid command')

    except KeyboardInterrupt:
        print('Thanks for listening :)')
        
        
dir_path('song directory path')
Steffo
  • 305
  • 5
  • 13
FIRE BOLT
  • 1
  • 2
  • 1
    Hint: to attract any attention you should consider making subject bit closer related to yiur question – Marcin Orlowski Jul 10 '22 at 16:16
  • Here's some [answers](https://stackoverflow.com/questions/13649884/play-music-using-pygame-but-no-sound) which might help you fix the first problem where no sound is playing. – Bunny Jul 10 '22 at 16:57

1 Answers1

1

Source of problem

When mixer is playing a song, you should wait in your program. Otherwise program will keep going and end eventually (you won't have time to hear anything).

Solution

After mixer.music.play() you should pause execution of program while the song is playing. mixer.music.get_busy() is a function used to test if a song is currently playing.

Full code

I made some minor insignificant changes to the structure of the program but you can still adapt my solution to your program.

import os
import time
import random
from pygame import mixer


def ValidInput(user_input):
    if(user_input == 'y' or user_input == 'n'):
        return 1
    return 0


def dir_path(path):
    mixer.init()
    songs_list = []
    lis = os.listdir(path)

    for i in lis:
        a = os.path.join(path, i)
        songs_list.append(a)

    # to enable shuffling
    shuffle = input('enable shuffling? y/n: ')
    if(not ValidInput(shuffle)):
        print('invalid command')

    if shuffle.lower() == 'y':
        already_played_songs = []  # index of songs already played
        t_end = time.time() + 60 * float(input('play time in minutes: '))

        while time.time() < t_end:
            a = random.randint(0, len(songs_list) - 1)
            if a not in already_played_songs:
                already_played_songs.append(a)
                mixer.music.load(songs_list[a])
                mixer.music.play()

                # keep playing current song until it finishes
                # or allocated time ends
                while(True):
                    if(time.time() >= t_end or not mixer.music.get_busy()):
                        break

            if len(already_played_songs) == len(songs_list):
                already_played_songs.clear()

        mixer.music.stop()  # stop any playing song at this point
        print('thanks for listening :)')
        return

    # to enable looping
    if shuffle.lower() == 'n':
        loopActivated = input('enable looping? y/n: ')
        if(not ValidInput(loopActivated)):
            print('invalid command')

        if loopActivated.lower() == 'y':

            sl_num = 1

            for i in lis:
                print(f'{sl_num}) {i}')
                sl_num += 1

            sl_no = int(input('sl_no of the song: '))
            loop_no = int(input('number of loops: '))
            loop_times = 0

            while loop_times < loop_no:
                if sl_no <= len(songs_list):
                    mixer.music.load(songs_list[sl_no - 1])
                    mixer.music.play()
                    while(True):
                        if(not mixer.music.get_busy()):
                            break  # song finished playing
                    loop_times += 1
                else:
                    print(f'only {len(songs_list)} songs are available')
                    loop_times = loop_no
                if loop_times == loop_no:
                    conn = input('continue listening? y/n: ')
                    if conn.lower() == 'y':
                        dir_path(path)
                    elif conn.lower() == 'n':
                        print('Thanks for listening :)')
                        return
                    else:
                        print('invalid command')
                        return

        #  play songs in order
        if loopActivated.lower() == 'n':
            for i in range(0, len(songs_list)):
                mixer.music.load(songs_list[i])
                mixer.music.play()
                while(True):
                    if(not mixer.music.get_busy()):
                        break  # song finished playing
            print('thanks for listening :)')
            return


dir_path('C:\\Users\\user\\Music')
Bunny
  • 1,180
  • 8
  • 22
  • Ayo, thanks a lottt!!! It's working perfectly fine. I was breaking my head in searching for solutions and other modules to play audio files with pause and stop options. Once again, thanks a lot :D – FIRE BOLT Jul 11 '22 at 14:47