A moving line on plot during audio play

7 次查看(过去 30 天)
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);

回答(1 个)

Samayochita
Samayochita 2025-2-27
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by