怎么用c语言播放特定目录里的wav文件?

怎么用c语言播放特定目录里的wav文件?,第1张

用C语言播放音乐,一般需要额外的库或者调用系统的API函数

以Windows为例,可以通过PlaySound函数播放wav格式的音乐。示例如下,代码在vc6.0中编译通过。

#include<stdio.h>

#include<windows.h>

#include<mmsystem.h>

#pragma

comment(lib,

"WINMM.LIB")

int

main()

{

PlaySound(TEXT("1.wav"),0,SND_FILENAME)

//1.wav是要播放的音乐文件

return

0

}

如果想播放mp3音乐可以使用如下代码。

注意:生成程序后,请在cmd中执行此程序,不要在vc/vs的IDE中运行。#include

<windows.h>

#include

<mmsystem.h>

#include

<stdio.h>

#pragma

comment(lib,

"Winmm.lib")

int

main(int

argc,

char

*argv[])

{

//绝对地址形式

TCHAR

fileName[]="ganlusi.mp3"

TCHAR

shortName[MAX_PATH]

GetShortPathName(fileName,shortName,sizeof(shortName)/sizeof(TCHAR))

TCHAR

cmd[MAX_PATH+10]

wsprintf(cmd,"play

%s",shortName)

mciSendString(cmd,NULL,

0,

NULL)

Sleep(5

*

60

*

1000)

//这里是防止一播放就结束做的延迟

return

0

}

C也能像matlab一样读取wav格式文件!

用外置库libsndfile,可以读取数据,频率,通道等等

以下是一段读取sample.wav,将数据存入double格式的array:

#include "sndfile.h"

#pragma comment(lib, "libsndfile-1.lib")

void readwav(double output[length]){

SNDFILE *sf

SF_INFO info

int num_channels

int num, num_items

double *buf

int f,sr,c

int i,j

info.format = 0

sf = sf_open("sample.wav",SFM_READ,&info)

if (sf == NULL){

printf("Failed to open the file.\n")

exit(-1)

}

f = info.frames

sr = info.samplerate

c = info.channels

printf("frames=%d\n",f)

printf("samplerate=%d\n",sr)

printf("channels=%d\n",c)

num_items = f*c

printf("num_items=%d\n",num_items)

buf = (double *)malloc(num_items*sizeof(double))

num = sf_read_double(sf,buf,num_items)

sf_close(sf)

printf("Read %d items\n",num)

for (i = 0i <numi += c){

for (j = 0j <c++j){

if ((i+j)<length) {

output[i+j] = buf[i+j]

}

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/7951978.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-11
下一篇 2023-04-11

发表评论

登录后才能评论

评论列表(0条)

保存