audd

package module
v0.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2023 License: MIT Imports: 15 Imported by: 7

README

GoDoc MIT licensed Twitter Follow

Table of Contents

Quick Start

Installation

go get github.com/AudDMusic/audd-go

API Token

To send >10 requests, obtain a token from our API Dashboard and change "test" to the obtained token in NewClient("test").

Sending the files

For recognize and recognizeWithOffset API methods, you have to send a file for recognition. There are two ways to send files to our API: you can either

  • 🔗 provide an HTTP URL of the file (our server will download and recognize the music from the file), or
  • 📤 post the file using multipart/form-data in the usual way a browser uploads files.

Recognize music from a file with a URL

It's straightforward.

package main

import (
	"fmt"
	"github.com/AudDMusic/audd-go"
)

func main()  {
    // initialize the client with "test" as a token
	client := audd.NewClient("test")
    // recognize music in audd.tech/example1.mp3 and return Apple Music, Deezer and Spotify metadata
	song, err := client.RecognizeByUrl("https://audd.tech/example1.mp3", "apple_music,deezer,spotify", nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s - %s.\nTimecode: %s, album: %s. ℗ %s, %s\n\n"+
		"Listen: %s\nOr directly on:\n- Apple Music: %s, \n- Spotify: %s,\n- Deezer: %s.",
		song.Artist, song.Title, song.Timecode, song.Album, song.Label, song.ReleaseDate,
		song.SongLink, song.AppleMusic.URL, song.Spotify.ExternalUrls.Spotify, song.Deezer.Link)
	if len(song.AppleMusic.Previews) > 0 {
		fmt.Printf("\n\nPreview: %s", song.AppleMusic.Previews[0].URL)
	}
}



If you run this code, you should see a result like

Imagine Dragons - Warriors.
Timecode: 00:40, album: Warriors. ℗ Universal Music, 2014-09-18

Listen: https://lis.tn/Warriors
Or directly on:
- Apple Music: https://music.apple.com/us/album/warriors/1440831203?app=music&at=1000l33QU&i=1440831624&mt=1,
- Spotify: https://open.spotify.com/track/1lgN0A2Vki2FTON5PYq42m,
- Deezer: https://www.deezer.com/track/85963521.

Preview: https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview118/v4/65/07/f5/6507f5c5-dba8-f2d5-d56b-39dbb62a5f60/mzaf_1124211745011045566.plus.aac.p.m4a

Recognize music from a local file

You can also send your local files to the API.

	file, _ := os.Open("/path/to/example.mp3/path/to/example.mp3")
	result, err := client.RecognizeByFile(file, "apple_music,deezer,spotify", nil)
	file.Close()

file in client.RecognizeByFile could be any variable that implements the io.Reader interface. If you have, e.g., var data []byte, you can use bytes.NewReader(data) as file.

There is also the Recognize function that accepts io.Reader and []byte for local files; string and url.URL for HTTP addresses of files.

Also, there's client.UseExperimentalUploading() that allows starting sending a file before it's loaded in the memory. Useful for large files sent to the enterprise endpoint (see the scanFiles example).

Searching the lyrics

It's easy with the FindLyrics function.

	result, err := client.FindLyrics("You were the shadow to my light", nil)
	if len(result) == 0 {
		fmt.Println("AudD can't find any lyrics by this query")
		return
	}
	firstSong := result[0]
	fmt.Printf("First match: %s - %s\n\n%s", firstSong.Artist, firstSong.Title, firstSong.Lyrics)

Use Cases

How you can use the AudD Music Recognition API:

Content analysis

Use our Music Recognition API to detect and identify songs in any audio content.

Create upload filters for UGC when the law requires. Find out what songs are used in any content on the Internet – or in the videos uploaded to your server. Recognize music from hours-long DJ mixes. Analyze the trends. Display the recognition results to your users. Use the metadata the API returns for your recommendation systems.

In-app music recognition and lyrics searching

Make your own music recognition application using AudD Music Recognition API. Detect and recognize music. Identify the songs your users are listening to and display the lyrics of the recognized songs. Or just let your users search lyrics by text.

Audio streams

Use AudD real-time music recognition service for audio streams to identify the songs that are being played on radio stations (or any other streams).

Monitor radio airplay, create radio song charts. Get real-time insights. If you have your own content DB, we can recognize songs that you upload (it's cheaper).

See https://streams.audd.io/ for more info.

License

The MIT License (MIT)

Documentation

Index

Constants

View Source
const (
	MainAPIEndpoint       string = "https://api.audd.io/"
	EnterpriseAPIEndpoint string = "https://enterprise.audd.io/"
)

API Endpoints

Variables

This section is empty.

Functions

This section is empty.

Types

type AppleMusicResult

type AppleMusicResult struct {
	Previews []struct {
		URL string `json:"url"`
	} `json:"previews"`
	Artwork struct {
		Width      int    `json:"width"`
		Height     int    `json:"height"`
		URL        string `json:"url"`
		BgColor    string `json:"bgColor"`
		TextColor1 string `json:"textColor1"`
		TextColor2 string `json:"textColor2"`
		TextColor3 string `json:"textColor3"`
		TextColor4 string `json:"textColor4"`
	} `json:"artwork"`
	ArtistName       string   `json:"artistName"`
	URL              string   `json:"url"`
	DiscNumber       int      `json:"discNumber"`
	GenreNames       []string `json:"genreNames"`
	DurationInMillis int      `json:"durationInMillis"`
	ReleaseDate      string   `json:"releaseDate"`
	Name             string   `json:"name"`
	ISRC             string   `json:"isrc"`
	AlbumName        string   `json:"albumName"`
	PlayParams       struct {
		ID   string `json:"id"`
		Kind string `json:"kind"`
	} `json:"playParams"`
	TrackNumber  int    `json:"trackNumber"`
	ComposerName string `json:"composerName"`
}

type Client

type Client struct {
	ApiToken     string
	Endpoint     string
	Experimental bool
}

func NewClient

func NewClient(apiToken string) *Client

func (*Client) AddStream

func (c *Client) AddStream(Url string, RadioID int, callbacks string, additionalParameters map[string]string) error

Adds a stream Send empty callbacks parameter for the default mode (callbacks will be sent after the song ends), send callbacks='before' for receiving callbacks when new songs just start playing on the stream

func (*Client) DeleteStream

func (c *Client) DeleteStream(RadioID int, additionalParameters map[string]string) error

Deletes a stream

func (*Client) FindLyrics

func (c *Client) FindLyrics(q string, additionalParameters map[string]string) ([]LyricsResult, error)

Finds the lyrics by the query

func (*Client) GetCallbackUrl

func (c *Client) GetCallbackUrl(additionalParameters map[string]string) (string, error)

Returns the URL the callbacks are sent to

func (*Client) GetStreams

func (c *Client) GetStreams(additionalParameters map[string]string) ([]Stream, error)

Returns all the streams

func (*Client) NewLongPoll added in v0.2.0

func (c *Client) NewLongPoll(RadioID int) LongPoll

Opens a LongPoll connection to the AudD API and receives the callbacks via LongPoll. The callbacks will be sent to both the callback URL and all the LongPoll listeners. Won't work unless some URL is set as the URL for callbacks. More info: docs.audd.io/streams/#longpoll

func (*Client) Recognize

func (c *Client) Recognize(v interface{}, Return string, additionalParameters map[string]string) (RecognitionResult, error)

Recognizes the music. Accepts files as io.Reader or []byte and file URLs as string or url.URL

func (*Client) RecognizeByFile

func (c *Client) RecognizeByFile(file io.Reader, Return string, additionalParameters map[string]string) (RecognitionResult, error)

Recognizes the music in the file

func (*Client) RecognizeByUrl

func (c *Client) RecognizeByUrl(Url string, Return string, additionalParameters map[string]string) (RecognitionResult, error)

Recognizes the music in the file available by the Url

func (*Client) RecognizeHumming

func (c *Client) RecognizeHumming(file io.Reader) ([]HummingResult, error)

[test feature] Recognizes the music in the file by humming

func (*Client) RecognizeHummingByUrl

func (c *Client) RecognizeHummingByUrl(Url string) ([]HummingResult, error)

[test feature] Recognizes the music in the file available by the Url by humming

func (*Client) RecognizeLongAudio

func (c *Client) RecognizeLongAudio(v interface{}, additionalParameters map[string]string) ([]RecognitionEnterpriseResult, error)

Recognizes the music in long (even hours-long or days-long) audio files Accepts files as io.Reader or []byte and file URLs as string or url.URL

func (*Client) RecognizeLongAudioByFile

func (c *Client) RecognizeLongAudioByFile(file io.Reader, additionalParameters map[string]string) ([]RecognitionEnterpriseResult, error)

Recognizes the music in long (even hours-long or days-long) audio files

func (*Client) RecognizeLongAudioByUrl

func (c *Client) RecognizeLongAudioByUrl(Url string, additionalParameters map[string]string) ([]RecognitionEnterpriseResult, error)

Recognizes the music in long (even hours-long or days-long) audio files available by the Url

func (*Client) Send

func (c *Client) Send(parameters map[string]string) ([]byte, error)

Sends a requests to the API

func (*Client) SendFile

func (c *Client) SendFile(file io.Reader, parameters map[string]string) ([]byte, error)

Sends a file request to the API

func (*Client) SendFileRequest

func (c *Client) SendFileRequest(file io.Reader, parameters map[string]string, v interface{}) error

Sends a request with a file and returns the result into the v

func (*Client) SendRequest

func (c *Client) SendRequest(parameters map[string]string, v interface{}) error

Sends a request returns the result into the v

func (*Client) SendUrl

func (c *Client) SendUrl(URL string, parameters map[string]string) ([]byte, error)

Sends a request with the URL specified

func (*Client) SendUrlRequest

func (c *Client) SendUrlRequest(url string, parameters map[string]string, v interface{}) error

Sends a request with a file URL and returns the result into the v

func (*Client) SetCallbackUrl

func (c *Client) SetCallbackUrl(Url string, additionalParameters map[string]string) error

Sets the URL for callbacks. The callbacks with the information about songs recognized in your streams will be sent to the specified URL

func (*Client) SetEndpoint

func (c *Client) SetEndpoint(APIEndpoint string)

Sets the endpoint used

func (*Client) SetStreamUrl

func (c *Client) SetStreamUrl(Url string, RadioID int, additionalParameters map[string]string) error

Sets the url of a stream

func (*Client) UseExperimentalUploading

func (c *Client) UseExperimentalUploading()

Call this if you want to actually start sending files without completely loading them in the memory Can lead to unexpected issues, like if the io.Reader returns an error while uploading is in progress, it can possibly still be counted as a request

type DeezerResult

type DeezerResult struct {
	ID             int    `json:"id"`
	Readable       bool   `json:"readable"`
	Title          string `json:"title"`
	TitleShort     string `json:"title_short"`
	TitleVersion   string `json:"title_version"`
	Link           string `json:"link"`
	Duration       int    `json:"duration"`
	Rank           int    `json:"rank"`
	ExplicitLyrics bool   `json:"explicit_lyrics"`
	Preview        string `json:"preview"`
	Artist         struct {
		ID            int    `json:"id"`
		Name          string `json:"name"`
		Link          string `json:"link"`
		Picture       string `json:"picture"`
		PictureSmall  string `json:"picture_small"`
		PictureMedium string `json:"picture_medium"`
		PictureBig    string `json:"picture_big"`
		PictureXl     string `json:"picture_xl"`
		Tracklist     string `json:"tracklist"`
		Type          string `json:"type"`
	} `json:"artist"`
	Album struct {
		ID          int    `json:"id"`
		Title       string `json:"title"`
		Cover       string `json:"cover"`
		CoverSmall  string `json:"cover_small"`
		CoverMedium string `json:"cover_medium"`
		CoverBig    string `json:"cover_big"`
		CoverXl     string `json:"cover_xl"`
		Tracklist   string `json:"tracklist"`
		Type        string `json:"type"`
	} `json:"album"`
	Type string `json:"type"`
}

type Error

type Error struct {
	ErrorCode    int    `json:"error_code"`
	ErrorMessage string `json:"error_message"`
}

func (Error) Error

func (e Error) Error() string

type FindLyricsResponse

type FindLyricsResponse struct {
	Response
	Result []LyricsResult `json:"result"`
}

type GetCallbackUrlResponse

type GetCallbackUrlResponse struct {
	Response
	Result string `json:"result"`
}

type GetStreamsResponse

type GetStreamsResponse struct {
	Response
	Result []Stream `json:"result"`
}

type HummingRecognitionResponse

type HummingRecognitionResponse struct {
	Response
	Result HummingRecognitionResult `json:"result"`
}

type HummingRecognitionResult

type HummingRecognitionResult struct {
	Count int             `json:"count"`
	List  []HummingResult `json:"list"`
}

type HummingResult

type HummingResult struct {
	Score  int    `json:"score"`
	Artist string `json:"artist"`
	Title  string `json:"title"`
}

type LongPoll added in v0.2.0

type LongPoll struct {
	ResultsChan chan StreamCallback
	// contains filtered or unexported fields
}

func (*LongPoll) Stop added in v0.2.0

func (lp *LongPoll) Stop()

Stops the LongPoll connection

type LyricsResult

type LyricsResult struct {
	SongId        int    `json:"song_id,string"`
	ArtistId      int    `json:"artist_id,string"`
	Title         string `json:"title"`
	TitleWithFeat string `json:"title_with_featured"`
	FullTitle     string `json:"full_title"`
	Artist        string `json:"artist"`
	Lyrics        string `json:"lyrics"`
	Media         string `json:"media"`
}

type MusicbrainzRecordings

type MusicbrainzRecordings struct {
	ID             string      `json:"id"`
	Score          int         `json:"score"`
	Title          string      `json:"title"`
	Length         int         `json:"length"`
	Disambiguation string      `json:"disambiguation"`
	Video          interface{} `json:"video"`
	ArtistCredit   []struct {
		Name   string `json:"name"`
		Artist struct {
			ID       string `json:"id"`
			Name     string `json:"name"`
			SortName string `json:"sort-name"`
		} `json:"artist"`
	} `json:"artist-credit"`
	Releases []struct {
		ID             string `json:"id"`
		Count          int    `json:"count"`
		Title          string `json:"title"`
		Status         string `json:"status"`
		Disambiguation string `json:"disambiguation,omitempty"`
		Date           string `json:"date"`
		Country        string `json:"country"`
		ReleaseEvents  []struct {
			Date string `json:"date"`
			Area struct {
				ID            string   `json:"id"`
				Name          string   `json:"name"`
				SortName      string   `json:"sort-name"`
				Iso31661Codes []string `json:"iso-3166-1-codes"`
			} `json:"area"`
		} `json:"release-events"`
		TrackCount int `json:"track-count"`
		Media      []struct {
			Position int    `json:"position"`
			Format   string `json:"format"`
			Track    []struct {
				ID     string `json:"id"`
				Number string `json:"number"`
				Title  string `json:"title"`
				Length int    `json:"length"`
			} `json:"track"`
			TrackCount  int `json:"track-count"`
			TrackOffset int `json:"track-offset"`
		} `json:"media"`
		ArtistCredit []struct {
			Name   string `json:"name"`
			Artist struct {
				ID             string `json:"id"`
				Name           string `json:"name"`
				SortName       string `json:"sort-name"`
				Disambiguation string `json:"disambiguation"`
			} `json:"artist"`
		} `json:"artist-credit,omitempty"`
		ReleaseGroup struct {
			ID             string   `json:"id"`
			TypeID         string   `json:"type-id"`
			Title          string   `json:"title"`
			PrimaryType    string   `json:"primary-type"`
			SecondaryTypes []string `json:"secondary-types"`
		} `json:"release-group,omitempty"`
	} `json:"releases"`
	Isrcs []string `json:"isrcs"`
	Tags  []struct {
		Count int    `json:"count"`
		Name  string `json:"name"`
	} `json:"tags"`
}

type NapsterResult

type NapsterResult struct {
	Type               string        `json:"type"`
	ID                 string        `json:"id"`
	Index              int           `json:"index"`
	Disc               int           `json:"disc"`
	Href               string        `json:"href"`
	PlaybackSeconds    int           `json:"playbackSeconds"`
	IsExplicit         bool          `json:"isExplicit"`
	IsStreamable       bool          `json:"isStreamable"`
	IsAvailableInHiRes bool          `json:"isAvailableInHiRes"`
	Name               string        `json:"name"`
	Isrc               string        `json:"isrc"`
	Shortcut           string        `json:"shortcut"`
	Blurbs             []interface{} `json:"blurbs"`
	ArtistID           string        `json:"artistId"`
	ArtistName         string        `json:"artistName"`
	AlbumName          string        `json:"albumName"`
	Formats            []struct {
		Type       string `json:"type"`
		Bitrate    int    `json:"bitrate"`
		Name       string `json:"name"`
		SampleBits int    `json:"sampleBits"`
		SampleRate int    `json:"sampleRate"`
	} `json:"formats"`
	LosslessFormats []interface{} `json:"losslessFormats"`
	AlbumID         string        `json:"albumId"`
	Contributors    struct {
		PrimaryArtist string `json:"primaryArtist"`
	} `json:"contributors"`
	Links struct {
		Artists struct {
			Ids  []string `json:"ids"`
			Href string   `json:"href"`
		} `json:"artists"`
		Albums struct {
			Ids  []string `json:"ids"`
			Href string   `json:"href"`
		} `json:"albums"`
		Genres struct {
			Ids  []string `json:"ids"`
			Href string   `json:"href"`
		} `json:"genres"`
		Tags struct {
			Ids  []string `json:"ids"`
			Href string   `json:"href"`
		} `json:"tags"`
	} `json:"links"`
	PreviewURL string `json:"previewURL"`
}

type RecognitionEnterpriseResponse

type RecognitionEnterpriseResponse struct {
	Response
	Result        []RecognitionEnterpriseResult `json:"result"`
	ExecutionTime string                        `json:"execution_time"`
}

type RecognitionEnterpriseResult

type RecognitionEnterpriseResult struct {
	Songs  []RecognitionResult `json:"songs"`
	Offset string              `json:"offset"`
}

type RecognitionResponse

type RecognitionResponse struct {
	Response
	Result  RecognitionResult `json:"result"`
	Warning *Warning          `json:"warning"`
}

type RecognitionResult

type RecognitionResult struct {
	Artist      string                  `json:"artist,omitempty"`
	Title       string                  `json:"title,omitempty"`
	Album       string                  `json:"album,omitempty"`
	ReleaseDate string                  `json:"release_date,omitempty"`
	Label       string                  `json:"label,omitempty"`
	Timecode    string                  `json:"timecode,omitempty"`
	SongLink    string                  `json:"song_link,omitempty"`
	Lyrics      *LyricsResult           `json:"lyrics,omitempty"`
	AppleMusic  *AppleMusicResult       `json:"apple_music,omitempty"`
	Deezer      *DeezerResult           `json:"deezer,omitempty"`
	MusicBrainz []MusicbrainzRecordings `json:"musicbrainz,omitempty"`
	Napster     *NapsterResult          `json:"napster,omitempty"`
	Spotify     *SpotifyResult          `json:"spotify,omitempty"`
	ISRC        string                  `json:"isrc,omitempty"`
	UPC         string                  `json:"upc,omitempty"`
	Score       int                     `json:"score,omitempty"`
	SongLength  string                  `json:"song_length,omitempty"`
	AudioID     int                     `json:"audio_id,omitempty"`
	StartOffset int                     `json:"start_offset,omitempty"`
	EndOffset   int                     `json:"end_offset,omitempty"`
}

type Response

type Response struct {
	Status string `json:"status"`
	Error  *Error `json:"error"`
}

type SpotifyResult

type SpotifyResult struct {
	Album struct {
		AlbumType string `json:"album_type"`
		Artists   []struct {
			ExternalUrls struct {
				Spotify string `json:"spotify"`
			} `json:"external_urls"`
			Href string `json:"href"`
			ID   string `json:"id"`
			Name string `json:"name"`
			Type string `json:"type"`
			URI  string `json:"uri"`
		} `json:"artists"`
		AvailableMarkets []string `json:"available_markets"`
		ExternalUrls     struct {
			Spotify string `json:"spotify"`
		} `json:"external_urls"`
		Href   string `json:"href"`
		ID     string `json:"id"`
		Images []struct {
			Height int    `json:"height"`
			URL    string `json:"url"`
			Width  int    `json:"width"`
		} `json:"images"`
		Name                 string `json:"name"`
		ReleaseDate          string `json:"release_date"`
		ReleaseDatePrecision string `json:"release_date_precision"`
		TotalTracks          int    `json:"total_tracks"`
		Type                 string `json:"type"`
		URI                  string `json:"uri"`
	} `json:"album"`
	Artists []struct {
		ExternalUrls struct {
			Spotify string `json:"spotify"`
		} `json:"external_urls"`
		Href string `json:"href"`
		ID   string `json:"id"`
		Name string `json:"name"`
		Type string `json:"type"`
		URI  string `json:"uri"`
	} `json:"artists"`
	AvailableMarkets []string `json:"available_markets"`
	DiscNumber       int      `json:"disc_number"`
	DurationMs       int      `json:"duration_ms"`
	Explicit         bool     `json:"explicit"`
	ExternalIds      struct {
		Isrc string `json:"isrc"`
	} `json:"external_ids"`
	ExternalUrls struct {
		Spotify string `json:"spotify"`
	} `json:"external_urls"`
	Href        string `json:"href"`
	ID          string `json:"id"`
	IsLocal     bool   `json:"is_local"`
	Name        string `json:"name"`
	Popularity  int    `json:"popularity"`
	TrackNumber int    `json:"track_number"`
	Type        string `json:"type"`
	URI         string `json:"uri"`
}

type Stream

type Stream struct {
	RadioID       int    `json:"radio_id"`
	URL           string `json:"url"`
	StreamRunning bool   `json:"stream_running"`
}

type StreamCallback added in v0.2.0

type StreamCallback struct {
	Status       string                   `json:"status"`
	Notification *StreamNotification      `json:"notification"`
	Result       *StreamRecognitionResult `json:"result"`
	Time         int64                    `json:"time"`
}

type StreamNotification added in v0.2.0

type StreamNotification struct {
	RadioID       int    `json:"radio_id"`
	StreamRunning bool   `json:"stream_running"`
	Code          int    `json:"notification_code"`
	Message       string `json:"notification_message"`
}

type StreamRecognitionResult added in v0.2.0

type StreamRecognitionResult struct {
	RadioID    int                 `json:"radio_id"`
	Timestamp  string              `json:"timestamp"`
	PlayLength int                 `json:"play_length,omitempty"`
	Results    []RecognitionResult `json:"results"`
}

type Warning

type Warning struct {
	ErrorCode    int    `json:"error_code"`
	ErrorMessage string `json:"error_message"`
}

func (Warning) Error

func (e Warning) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL