Guide: Playing an audio file stored on your device using Tauri

I'm currently developing an mp3 (audio) player using Tauri and Vue.js.

Despite trying various solutions, none of them seem to work for me.

The player is implemented with a simple video tag :

<video ref="video" :key="queryUrl" controls>
    <source
      :key="queryUrl"
      :src="sourceUrl"
      ref="source"
      type="audio/mpeg"
    >
</video>

Initially, I attempted to change the source like this:

const appDataDirPath = await appDataDir();
const filePath = await join(appDataDirPath, 'test.mp3');
sourceUrl.value = filePath;

However, I encountered the following error:

Not allowed to load local resource: file:///C:/Users/hangel/AppData/Roaming/com.tauri.dev/test.mp3

Even utilizing Audio from javascript resulted in the same issue:

const audio = new Audio('C:\\Users\\hangel\\AppData\\Roaming\\com.tauri.dev\\test.mp3');
// Not allowed to load local resource

Next, I decided to try out the convertFileSrc function from Tauri's documentation:

const appDataDirPath = await appDataDir();
const filePath = await join(appDataDirPath, 'test.mp3');
const assetUrl = convertFileSrc(filePath);

source.value.src = assetUrl;
video.value.appendChild(source.value);
video.value.load();

Unfortunately, I still received an error:

GET net::ERR_CONNECTION_REFUSED

For my final attempt, I tried using the readBinaryFile function from Tauri:

However, I am unsure how to proceed with the content of my file (Uint8Array).

const content = await readBinaryFile('test.mp3', { dir: BaseDirectory.AppData });
// returns a Uint8Array
// what to do with this array ?

Answer №1

If you're looking to load local audio (media) files, consider using the convertFileSrc method provided by Tauri.

For detailed information, refer to the official documentation:

Follow these steps to effectively utilize this method:

To use the convertFileSrc method, modify the tauri.conf.json file and include the protocol in tauri.allowlist:

  "protocol": {
    "all": true,
    "asset": true,
    "assetScope": ["**"]
  }

Additionally, within the tauri.conf.json, update the tauri.allowlist section with:

    "security": {
      "csp": "default-src 'self'; media-src 'self' asset: https://asset.localhost;"
    }

You can then proceed to load the mp3 file as demonstrated below:

  import { appDataDir, join } from '@tauri-apps/api/path';
  import { convertFileSrc } from '@tauri-apps/api/tauri';

  const appDataDirPath = await appDataDir();
  const filePath = await join(appDataDirPath, 'test.mp3');
  const musicUrl = convertFileSrc(filePath);

  source.value.src = musicUrl;
  video.value.appendChild(source.value);
  video.value.load();

Answer №2

Perhaps you should consider adjusting your security settings, specifically your CSP.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the excessive memory usage of (JS)Strings when loading complex .obj files in AFrame and Three.js?

Our webscene is quite complex, with dynamically loaded .obj and .mtl files. When comparing the scene without any objects to one with multiple objects, we noticed a strange issue: In Firefox's memory heap, most of the memory (>100MB for 5 objects) ...

Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result. Here is my scenario: In my form.html file: ...

Creating a JavaScript function that calculates the sum of values in a table

Here is a snippet of my HTML code: <TR Row="1" CLASS="ThemeAlignCenter"> <TD id="wrdActive_Row1" style="width: 50px" CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD> .. ...

Customize Vue or Nuxt by including a highly detailed tag in the <head> section

Trying to generate static page templates using Vue/Nuxt but struggling to find a way to insert a very specific tag into the head section of each generated page. It's not a meta, script, style, or link tag, and it appears that the options in nuxt.confi ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

Tips for formatting the date obtained from Element-UI

Incorporating the datepicker from Element Ui allows for user selection of a range in dates. Once the user inputs their selections into the datepicker, I receive an array with two String elements: ['2018-01', '2019-02']. This array does ...

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

On the second attempt to call setState within the componentDidMount method, it is not functioning as expected

As a newcomer, I am delving into the creation of a memory game. The main objective is to fetch data from an API and filter it to only include items with image links. On level one of the game, the task is to display three random images from the fetched data ...

Utilizing a dropdown selection value to filter a list in JavaScript

I have an array of objects where I need to filter based on a dropdown selection. const itemsList=[{ "id":"123", "problems":{ "causes":[ { "SSEnabled": true, "IndusEnabled": false, "LogEnabled": true } ] } ...

Guide on crafting a scrollable and touch-responsive grid using CSS and JavaScript

I am seeking guidance on creating a grid with a variable number of columns and rows. It should be contained within a separate div and should not interfere with other objects or alter the parent's size. The grid needs to be square and I am currently u ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...

The SvelteKit server successfully loaded data, displaying it on the sources/index page in the Chrome

I am currently in the process of developing a basic web application that utilizes self-hosted Pocketbase on the backend and SvelteKit as a meta framework. Recently, I discovered that the data loaded by my server is visible in the browser's sources/in ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

Vue app running on node server with IIS gives 404 error: page not found

Running a Vue app on a node server and trying to implement a URL redirect using IIS has resulted in a puzzling issue. Everything works perfectly fine when the app is accessed locally with the specified port: https://i.sstatic.net/5bfBu.png However, upon a ...

Dynamic Sizing of Elements + Adaptive Text Overlay

There were 2 obstacles I encountered when trying to create an image-based drop-down menu : No matter how much effort I put in, I couldn't figure out how to make a flexed element inside a container maintain the same height as the adjacent element. [ ...

Having trouble with the page redirection issue? Here's how you can troubleshoot and resolve

My goal is to restrict access to both the user home and admin dashboard, allowing access only when logged in. Otherwise, I want to redirect users to the login or admin login page. import { NextResponse } from 'next/server' import { NextRequest } ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

Having trouble seeing the output on the webpage after entering the information

I can't seem to figure out why the result is not displaying on the HTML page, so for now I have it set up as an alert. <h1>Factorial Problem</h1> <form name="frm1"> Enter any number :<input type="text" name="fact1"& ...