ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

How to read and play any audio file using Python

Автор: buckmasterinstitute

Загружено: 2022-05-13

Просмотров: 9357

Описание: Created and recorded by Jeffano John, May 2022

Music: Call of the void, by Justin Miles, https://lmms.io/lsp/?action=show&file...

Script:

Reading a specific audio file is simple but being able to read different types of audio files and play is where the challenge is. This video will go through the code on how to read multiple audio files and play them. In the tutorial we are working with Python. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. An audio file is a record of captured sound that can be played back. There are many different types of audio files such as MP3, FLAC, WAV etc.

So, in this tutorial, you will see how to read an audio file from a folder and play it using Python.

First, we need to install the packages:
pathlib which is used to find the directory of a folder
os package is used to read the folder and the contents within it
pygame package has a function that can be used to start and stop the music from playing

Next, we want to set a variable for the path directory. In my case the music folder is within multiple folders, so the directory is quite long. As you can see this is where my music file is located.

Next, I want to create a variable initial_count and set it to 0. This is to count how many files are in the folder.

Then create a for loop to go through each file and use the if statement using this function to check if it is a file. For the for loop, you use
for path in pathlib.Path("/Users/Jeffano/Desktop/TheBuckmasterInstitute/PythonVideoProjects/ReadPlayAudioFiles/Music").iterdir():

Then the if statement is:
if path.is_file():
initial_count += 1
The count will be used to count how many files are there.

Then a print statement is used to display the number of files.
print('\nThere are', initial_count, 'audio files\n')

Next using the os package, we can use listdir function to read the file names and store it under the variable “list”. Then we can print the list.
list = os.listdir('/Users/Jeffano/Desktop/TheBuckmasterInstitute/PythonVideoProjects/ReadPlayAudioFiles/Music')
print(list)

Next, we can ask the user an input of their song choice and store it under the variable “song”.
song = input("\nEnter The Song File You Wish To Play: ")

Then under the variable “file”, we can use the OS package to edit the directory to pick a specific song. This calls the inputdirectory variable and adds the song variable at the end of it.
file = os.path.join(inputdirectory, song)

Next, we initialize pygame and the loads the song into the pygame.mixer.music function.
pygame.init()
pygame.mixer.music.load(file)

Then a while loop is created. The while loop will ask the user to play or stop the song and if the user is done, then to exit the program. N is the variable that is used to read the user input.

while True:
n = input("Type Play or Stop to start or stop the song. \nType Exit to stop the program:\n")
if n "play" :
pygame.mixer.music.play()
elif n "stop":
pygame.mixer.music.pause()
elif n == "exit":
exit()

If n = plays, the
pygame.mixer.music.play()
is used and the song starts to play.

If n = stop, the
pygame.mixer.music.pause()
is used and the song stops.

Lastly if n = exit, the
exit()
function is used and stops the code.

Show the code being used with different audio files.

This is how we can use python to read and play different audio files. I hope this was helpful and have a wonderful day.

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
How to read and play any audio file using Python

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

How to Play Audio Files (Sound Effects and Music) in Python Using Pygame (Mp3 and Others)

How to Play Audio Files (Sound Effects and Music) in Python Using Pygame (Mp3 and Others)

Python Audio Processing Basics - How to work with audio files in Python

Python Audio Processing Basics - How to work with audio files in Python

Librosa  Audio and Music Signal Analysis in Python | SciPy 2015 | Brian McFee

Librosa Audio and Music Signal Analysis in Python | SciPy 2015 | Brian McFee

How to Start Coding | Programming for Beginners | Learn Coding | Intellipaat

How to Start Coding | Programming for Beginners | Learn Coding | Intellipaat

Functions in Python are easy 📞

Functions in Python are easy 📞

Трамп объявил о прекращении огня / Конец российского наступления?

Трамп объявил о прекращении огня / Конец российского наступления?

React Leaflet Tutorial for Beginners (2023)

React Leaflet Tutorial for Beginners (2023)

Parallel and Perpendicular Lines, Transversals, Alternate Interior Angles, Alternate Exterior Angles

Parallel and Perpendicular Lines, Transversals, Alternate Interior Angles, Alternate Exterior Angles

Итоги дня | Обыски у главы МВД | Взрыв в центре Москвы | Кремль про конфликт с Баку

Итоги дня | Обыски у главы МВД | Взрыв в центре Москвы | Кремль про конфликт с Баку

“Патриоты” не летят, а гражданство США — отбирают: Вашингтон начинает чистку /№971/ Юрий Швец

“Патриоты” не летят, а гражданство США — отбирают: Вашингтон начинает чистку /№971/ Юрий Швец

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]