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 Center および File ExchangeAudio and Video Data についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by