How to generate sound in Matlab?
조회 수: 64 (최근 30일)
이전 댓글 표시
I want to generate sound for my sine wave but the sound did not come out. Is there something wrong with my code? Really need help, thanks.
fsampling = 1000;
f1 = 20;
f2 = 100;
f3 = 300;
fn1 = 150;
fn2 = 200;
fn1_normfreq = fn1/(fsampling/2);
fn2_normfreq = fn2/(fsampling/2);
x1 = cos(2*pi*f1*[0:1/fsampling:1.23]);
x2 = cos(2*pi*f2*[0:1/fsampling:1.23]);
x3 = cos(2*pi*f3*[0:1/fsampling:1.23]);
x = x1 + x2 + x3;
x(end) = [];
[b,a] = butter(2,[fn1_normfreq fn2_normfreq],'bandpass');
filtered_noise = filter(b,a,randn(1, length(x)*2));
y = (x + 0.5*filtered_noise(500:500+length(x)-1))/length(x)*2;
sound(y,fsampling)
댓글 수: 0
채택된 답변
Chad Greene
2015년 11월 17일
Use
soundsc(y,fsampling)
which scales the sound before playing it.
댓글 수: 3
Chad Greene
2015년 11월 17일
You could repeat y as many times as you want. This plays y five times in a row:
y_five_times = repmat(y,1,5);
soundsc(y_five_times,fsampling)
To get y to play for a specified amount of time, you'll have to repeat y enough times to fill the desired length, then only play the number of samples necessary to meet the time requirement:
% Enter how long you want the signal to be in seconds:
Desired_length = 7.5;
% Number of samples necessary to make the sound the desired length:
num_samples = round(Desired_length*fsampling);
% Number of times y must be repeated:
num_repeats = ceil(num_samples/length(y));
% Create a vector of y repeated as many times as necessary:
y_long = repmat(y,1,num_repeats);
% Clip y_long to be exactly the desired length:
y_long_clipped = y_long(1:num_samples);
% Play the sound:
soundsc(y_long_clipped,fsampling)
추가 답변 (1개)
Image Analyst
2015년 11월 17일
For what it's worth, I have attached a demo that creates a weird sound and plays it.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Audio I/O and Waveform Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!