/*************************************************************************
*	"sndplay.cci"	: 音声データの再生
*************************************************************************/


int		CCI_sndPlay(int argc, char **argv)
{
	char	*fp;
	char	*fdl;
	char	*dlg;
	char	*fn, buf[128], *dat;
	int		ret, ch, mute_sw, x, y;
	long	siz;

	if ( argc > 1 )
	{
		fn = argv[1];
	} else
	{
		if ( (fdl = FDL_open(0)) == NULL )
			return (ERR);
		FDL_set_title( fdl,"SND PLAY");
		FDL_set_wildcard( fdl, "*.snd");
		ret = FDL_start(fdl);
		fn  = FDL_get_filename(fdl);
		if ( ret == NORMAL && strlen(fn) > 0 )
		{
			strcpy( buf, fn );
			fn = buf;
		} else
			ret = ERR;
		FDL_close(fdl);
		if ( ret != NORMAL )
			return (ERR);
	}

	if ( (fp = FM_fopen(fn,"rb")) == NULL )
	{
		DLG_tmpMsgTime( DLGPOS_MOS_SET_CENTER, DLGPOS_MOS_SET_CENTER,
		    C_MBLACK, C_DLGBASE, COLMIX(C_ERROR,C_GRAY),
		    3, "file open error!! (%s)", fn );
		return (ERR);
	}
	fseek(fp, 0, SEEK_END);
	siz = ftell(fp);					/* ファイルサイズの取得		*/
	rewind(fp);
	if( (dat = malloc(siz)) == NULL )	/* データ読み込み領域の確保	*/
	{
		FM_fclose(fp);
		DLG_tmpMsgBox ( DLGPOS_MOS_SET_CENTER, DLGPOS_MOS_SET_CENTER,
		    C_MBLACK, C_DLGBASE, COLMIX(C_ERROR,C_GRAY),
		    "Memory allocation error!! (size %u)", siz );
		return (ERR);
	}
	fread( dat, siz, 1, fp );
	FM_fclose(fp);

	dlg = DLG_msgOpen( DLGPOS_MOS_SET_CENTER,DLGPOS_MOS_SET_CENTER,
	    6*40,12*6, C_MBLACK,C_DLGBASE,COLMIX(C_INFO,C_GRAY),
	    "SND PLAYER");

	DLG_msgSetConfig( dlg, 4, 6, 12 );
	DLG_msgClear( dlg, C_HWHITE);
	DLG_msgPrintf(dlg,"\r\n" );
	DLG_msgPrintf(dlg,"SND DATA FILE : %s\r\n", fn );
	DLG_msgPrintf(dlg,"    DATA SIZE : %8u\r\n", siz );
	DLG_msgPrintf(dlg,"    BASE NOTE : %d\r\n", dat[28]&127 );

	SND_get_elevol_mute( &mute_sw );	/* ミュート状態の取得	*/
	mute_sw |= 1;						/* PCM音源ミュート解除	*/
	SND_elevol_mute( mute_sw );			/* ミュート設定			*/

	SND_pcm_abort();
	SND_pcm_mode_set(1);
	ch = 71;
	SND_pan_set(ch,64);							/* パンポット	*/
	SND_pitch_change(ch,8192);					/* ピッチベンド	*/
	SND_volume_change(ch,127);					/* ボリューム	*/
	SND_pcm_play(ch, dat[28] & 127, 127, dat);	/* 再生			*/
	while ( SND_pcm_status(ch) != 0 )
	{	if ( EVT_kbhit() || EVT_mos_pget(&x,&y) )
		{
			DLG_msgPrintf(dlg,"\r\nAbort...\r\n" );
			break;
		}
	}
	SND_pcm_play_stop(ch);

	DLG_msgClose( dlg );

	free(dat);

	return (NORMAL);
}
