How to play and stop audio file
Show older comments
I want to make a gui with two buttons play and stop audio file how can i do that
Answers (1)
EngEdgarHS
on 21 May 2017
Edited: EngEdgarHS
on 21 May 2017
I will show two different methods I know:
1º method
In function OpeningFCN contained in .m file created by figure of GUI, type:
[y, Fs] = audioread('your_audio_file.mp3');
Where y is the sampled data returned by reading the audio file and Fs is the sample rate for y. It's not necessary to be just audios in .mp3 or .wav.
In function Callback of the button created to play the song, type:
sound(y, Fs, nBits);
nBits usually is seted to 16 bits.
And then, in function Callback of the button created to stop the song, type:
clear sound;
---
2º method
This method is the best, in my opinion. In function OpeningFCN contained in .m file created by figure of GUI, type:
[y, Fs] = audioread('your_audio_file.mp3');
player = audioplayer(y, Fs);
add four buttons in your figure: one for play, one for pause, one for resume and one for stop.
In function Callback of the button created to play the song, type:
play(player);
In function Callback of the button created to pause the song, type:
pause(player);
In function Callback of the button created to resume the song, type:
resume(player);
And in function Callback of the button created to stop the song, type:
stop(player);
P.S: Don't forget to declare variables as global.
Easy, don't? Regardles
7 Comments
Walter Roberson
on 21 May 2017
global variables are error prone, and the slowest of all the variables.
EngEdgarHS
on 25 May 2017
Edited: EngEdgarHS
on 25 May 2017
Then, Fs and y don't need be global in first method? Interesting!
Thanks Walter.
Rainaire Hansford
on 5 Nov 2018
Ok so the [y,Fs] method didn't work so am I missing something also I forgot how to make the buttons function lol
Manoj Kumar
on 1 May 2019
many many thanks
b
on 25 Jun 2019
How to adjust the volume so that one file plays at volume1 and the second file plays at volume2 ?
zainab ne
on 7 Jun 2020
Where do I have to declare global y Fs ? I am extremely new to Matlab. It keeps producing an error “error while evaluating UIControl Callback” Help pls
Walter Roberson
on 7 Jun 2020
In the code for the second approach, it would be player that you need to share, because you would create the player and start playing in one callback, and you need access to the player again in another callback in order to be able to stop or pause it.
Categories
Find more on Audio and Video Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!