ycliper

Популярное

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

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

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

Топ запросов

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

How to read and play any audio file using Python

Автор: buckmasterinstitute

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

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

Описание: 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

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

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

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

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

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

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

Пайтон для начинающих - Изучите Пайтон за 1 час

Пайтон для начинающих - Изучите Пайтон за 1 час

Обработка аудиоданных на Python

Обработка аудиоданных на 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

Solving the 3-Body Problem in Python!

Solving the 3-Body Problem 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

Автоматизируйте свою работу с помощью Python

Автоматизируйте свою работу с помощью Python

[Успокаивающее расслабляющее сон] Медитация - Мономан

[Успокаивающее расслабляющее сон] Медитация - Мономан

Filtering Noise from President Trump's Press Conference (MATLAB Audio Filtering)

Filtering Noise from President Trump's Press Conference (MATLAB Audio Filtering)

Full Beginners Guide to Animating in MMD (2023)

Full Beginners Guide to Animating in MMD (2023)

Is Zorin OS the Best Windows Replacement?

Is Zorin OS the Best Windows Replacement?

Как создать простой синтезатор звука на Python

Как создать простой синтезатор звука на Python

Top 50 Christmas Songs of All Time 🎄 Best Christmas Music Playlist

Top 50 Christmas Songs of All Time 🎄 Best Christmas Music Playlist

Функции в Python — это просто 📞

Функции в Python — это просто 📞

Wielki Protest w Brukseli, Oriesznik na Białorusi i Gigantyczny Kredyt dla Ukrainy!

Wielki Protest w Brukseli, Oriesznik na Białorusi i Gigantyczny Kredyt dla Ukrainy!

Raspberry Pi - Autostart Application with Splash Screen

Raspberry Pi - Autostart Application with Splash Screen

Three Jupyter Notebooks for the STFT

Three Jupyter Notebooks for the STFT

AI Text to Speech in 10 Minutes with Python and Watson TTS

AI Text to Speech in 10 Minutes with Python and Watson TTS

My First Year of Western Engineering

My First Year of Western Engineering

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



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



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