A moving line on plot during audio play

조회 수: 6 (최근 30일)
Mayank Amencherla
Mayank Amencherla 2014년 1월 4일
답변: Samayochita 2025년 2월 27일
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.

카테고리

Help CenterFile Exchange에서 Audio and Video Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by