A moving line on plot during audio play
7 views (last 30 days)
Show older comments
I want a moving line across the audio plot while it is simultaneously playing the audio. How would I implement that?
%Code
[sig,fs] = audioread('audiofile.wav'); player = audioplayer(sig,fs); play(player);
0 Comments
Answers (1)
Samayochita
on 27 Feb 2025
Hi Mayank,
I understand that you are trying to display a moving vertical line that progresses across the plot in real-time as the audio plays.
The first two lines of code that you have written are correct. Additionally, you can use a while loop to check if the audio is still playing using “isplaying” function
(https://www.mathworks.com/help/matlab/ref/audioplayer.isplaying.html) and update the vertical line “hLine” dynamically. The “pause” function
(https://in.mathworks.com/help/matlab/ref/pause.html) is used to pause the execution for 10 milliseconds and update the plot smoothly.
Here is the modified code for your reference:
% Read the audio file
[sig, fs] = audioread('audiofile.wav');
% Create an audioplayer object
player = audioplayer(sig, fs);
% Time vector for the audio signal
t = linspace(0, length(sig) / fs, length(sig));
% Plot the audio waveform
figure;
plot(t, sig);
xlabel('Time (s)');
ylabel('Amplitude');
title('Audio Playback with Moving Line');
hold on;
% Initialize the moving line
hLine = line([0 0], ylim, 'Color', 'r', 'LineWidth', 2);
% Start audio playback
play(player);
% Update the moving line position during playback
while isplaying(player)
% Get current playback time
currentTime = player.CurrentSample / fs;
% Update the line position
set(hLine, 'XData', [currentTime currentTime]);
% Pause for a short duration to allow updates
pause(0.01);
end
I hope you found this helpful.
0 Comments
See Also
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!